Reputation: 601
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?
Upvotes: 9
Views: 21253
Reputation: 154
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();
Upvotes: 0
Reputation:
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";
}
Upvotes: 7
Reputation: 1893
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
Upvotes: 11