7

我能够使用以下方法获取用户名:

@Autowired
 private HttpServletRequest request;
 Principal user = request.getUserPrincipal();
 mqMessage.setUserName(user.getName());

但我想获取登录用户的名字和姓氏。我怎样才能得到ff。使用 SpringBoot keycloak 适配器的用户信息?

4

3 回答 3

10
        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

于 2018-03-06T10:29:14.050 回答
6

使用 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";
}
于 2020-08-17T16:29:28.537 回答
0

我们可以使用 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();
于 2021-10-27T17:15:58.253 回答