How to get userinfo in springboot using keycloak?
Asked Answered
S

3

9

I was able to get the username by using:

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

But I want to get the firstName & lastName of the user logged in. How can i get the ff. userinfo using SpringBoot keycloak adapter?

Speculation answered 5/3, 2018 at 7:21 Comment(0)
H
11
        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();

You can make use of the above code snippet to get the first and the last name This is from 2.4.0

Hurrah answered 6/3, 2018 at 10:29 Comment(0)
T
7

Implemented with Keycloak 11 and Spring security

More references: 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";
}
Termination answered 17/8, 2020 at 16:29 Comment(0)
S
0

we can use SecurityContextHolder for getting user details.

 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();
Subsocial answered 27/10, 2021 at 17:15 Comment(2)
auth is always null for meLucius
@YamenNassif you must be authenticated for getting Authentication from SecurityContextHolder. Maybe check your spring security config?Piers

© 2022 - 2024 — McMap. All rights reserved.