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
?
A user would have to be authenticated before seeing some application content. After successful authentication, access token would be given to client (can be application gateway or ui application) and then role can be extracted from it and used. How the role can be extracted from the JWT Access token?
Keycloak roles are defined in a dedicated namespace so that all users with the same roles have identical permissions in that namespace. In other words, realm-level roles are a global namespace for a given realm, while client roles are namespaces intended for specific applications.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With