📜  使用接收到的访问令牌检索 Keycloak 用户数据 - 无论代码示例

📅  最后修改于: 2022-03-11 14:58:08.798000             🧑  作者: Mango

代码示例1
Requires 


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


private Set selectResourceRoles(String keycloakResource,HttpServletRequest request ) {
          Set 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();
    }