How to use Spring Security RemoteTokenService with Keycloak
I found a solution by myself just after formulating this question here. Sometimes it helps to try to express a problem.
The solution is to override the DefaultAccessTokenConverter to teach him how to read the "realm_access" field. Its ugly but it works:
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId("demo-client");
RemoteTokenServices tokenServices = new RemoteTokenServices();
tokenServices.setCheckTokenEndpointUrl(
"http://localhost:8280/auth/realms/demo-realm/protocol/openid-connect/token/introspect");
tokenServices.setClientId("demo-client");
tokenServices.setClientSecret("80e19056-7770-4a4a-a3c4-06d8ac8792ef");
tokenServices.setAccessTokenConverter(new KeycloakAccessTokenConverter());
resources.tokenServices(tokenServices);
}
private class KeycloakAccessTokenConverter extends DefaultAccessTokenConverter {
@Override
public OAuth2Authentication extractAuthentication(Map<String, ?> map) {
OAuth2Authentication oAuth2Authentication = super.extractAuthentication(map);
Collection<GrantedAuthority> authorities = (Collection<GrantedAuthority>) oAuth2Authentication.getOAuth2Request().getAuthorities();
if (map.containsKey("realm_access")) {
Map<String, Object> realm_access = (Map<String, Object>) map.get("realm_access");
if(realm_access.containsKey("roles")) {
((Collection<String>) realm_access.get("roles")).forEach(r -> authorities.add(new SimpleGrantedAuthority(r)));
}
}
return new OAuth2Authentication(oAuth2Authentication.getOAuth2Request(),oAuth2Authentication.getUserAuthentication());
}
}
Via keycloak admin console you can create a token mapper of type User Realm Role with claim name "authorities" for your client "demo-client". Then the access token contains the role names in this attribute and no custom DefaultAccessTokenConverter is needed.