的
我能够通过以下方式获取用户名:
@Autowired
private HttpServletRequest request;
Principal user = request.getUserPrincipal();
mqMessage.setUserName(user.getName());
但是我想获取登录用户的名字和姓氏。如何使用 SpringBoot Keycloak 适配器获取 ff. 用户信息?
KeycloakAuthenticationToken token = (KeycloakAuthenticationToken) request.getUserPrincipal();
KeycloakPrincipal principal=(KeycloakPrincipal)token.getPrincipal();
KeycloakSecurityContext session = principal.getKeycloakSecurityContext();
AccessToken accessToken = session.getToken();
username = accessToken.getPreferredUsername();
emailID = accessToken.getEmail();
lastname = accessToken.getFamilyName();
firstname = accessToken.getGivenName();
realmName = accessToken.getIssuer();
Access realmAccess = accessToken.getRealmAccess();
roles = realmAccess.getRoles();
您可以使用上面的代码片段来获取名字和姓氏这是从 2.4.0 开始
使用 Keycloak 11 和 Spring 安全性实现
更多参考资料: https://www.keycloak.org/docs/latest/securing_apps/#_spring_security_adapter
import java.security.Principal;
/** More imports */
@GetMapping("/userinfo")
public String userInfoController(Model model, Principal principal) {
KeycloakAuthenticationToken keycloakAuthenticationToken = (KeycloakAuthenticationToken) principal;
AccessToken accessToken = keycloakAuthenticationToken.getAccount().getKeycloakSecurityContext().getToken();
model.addAttribute("username", accessToken.getGivenName());
return "page";
}
我们可以使用SecurityContextHolder来获取用户详细信息。
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
KeycloakPrincipal principal = (KeycloakPrincipal)auth.getPrincipal();
KeycloakSecurityContext session = principal.getKeycloakSecurityContext();
AccessToken accessToken = session.getToken();
String username = accessToken.getPreferredUsername();
String emailID = accessToken.getEmail();
String lastname = accessToken.getFamilyName();
String firstname = accessToken.getGivenName();
String realmName = accessToken.getIssuer();
AccessToken.Access realmAccess = accessToken.getRealmAccess();