Answers for "Retrieve Keycloak user data using received access token"

0

Retrieve Keycloak user data using received access token

Requires 


import org.keycloak.KeycloakPrincipal;
import org.keycloak.KeycloakSecurityContext;
import org.keycloak.representations.AccessToken;


private Set<String> selectResourceRoles(String keycloakResource,HttpServletRequest request ) {
    	  Set<String> roles = new HashSet<>();
    	  AccessToken.Access resourceAccess =
    	      getKeycloakSecurityContext(request).getToken().getResourceAccess(keycloakResource);
    	  if (resourceAccess != null && resourceAccess.getRoles() != null) {
    	    roles.addAll(resourceAccess.getRoles());
    	  }
    	  return Collections.unmodifiableSet(roles);
    }
    
    private KeycloakSecurityContext getKeycloakSecurityContext(HttpServletRequest request){
    	KeycloakPrincipal principal = (KeycloakPrincipal) request.getUserPrincipal();
		 
    	return  principal.getKeycloakSecurityContext();
    }
    
    private AccessToken getAccessToken(HttpServletRequest request){
    	KeycloakPrincipal principal = (KeycloakPrincipal) request.getUserPrincipal();
		 
    	return  principal.getKeycloakSecurityContext().getToken();
    }
    
    private String getLoggedinUser(HttpServletRequest request){
    	KeycloakPrincipal principal = (KeycloakPrincipal) request.getUserPrincipal();
	    System.out.println(String.format("User '%s' with email '%s' made request to CustomerService REST endpoint", getAccessToken(request).getPreferredUsername(), getAccessToken(request).getEmail()));

    	return  principal.getKeycloakSecurityContext().getIdToken().getSubject();
    }
Posted by: Guest on June-15-2021

Code answers related to "Retrieve Keycloak user data using received access token"

Browse Popular Code Answers by Language