Reputation: 3374
I am trying to get a list of roles assigned to a particular user from a Spring Boot application secured with keycloak.
I have declared an AccessToken
bean in the KeycloakWebSecurityConfigurerAdapter
configuration class as follows:
@Configuration
@EnableWebSecurity
@ComponentScan(basePackageClasses = KeycloakSecurityComponents.class)
public class KeycloakSecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
//other config code
@Bean
@Scope(scopeName = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public AccessToken accessToken() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
return ((KeycloakSecurityContext) ((KeycloakAuthenticationToken) request.getUserPrincipal()).getCredentials()).getToken();
}
}
Now I can autowire the AccessToken
in the controller and I am able to get the information like ID and username but how do I get the list of roles assigned to the user using the AccessToken
?
Upvotes: 7
Views: 11189
Reputation: 9633
for resource role mapping use
AccessToken.Access access = accessToken.getResourceAccess(clientId);
Set<String> roles = access.getRoles();
for realm role mappings use
AccessToken.Access access = accessToken.getRealmAccess();
Set<String> roles = access.getRoles();
Upvotes: 5