我能够使用以下方法获取用户名:
@Autowired
private HttpServletRequest request;
Principal user = request.getUserPrincipal();
mqMessage.setUserName(user.getName());
但我想获取登录用户的名字和姓氏。我怎样才能得到ff。使用 SpringBoot keycloak 适配器的用户信息?
我能够使用以下方法获取用户名:
@Autowired
private HttpServletRequest request;
Principal user = request.getUserPrincipal();
mqMessage.setUserName(user.getName());
但我想获取登录用户的名字和姓氏。我怎样才能得到ff。使用 SpringBoot keycloak 适配器的用户信息?
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();