📅  最后修改于: 2022-03-11 14:58:08.798000             🧑  作者: Mango
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();
}