From 783cf00f3eee9a2928feecc9569c8e85279e3ce6 Mon Sep 17 00:00:00 2001 From: little-pinecone Date: Wed, 22 Dec 2021 15:42:16 +0100 Subject: [PATCH] Add example for mapping role names between Keycloak and Spring Boot * use SimpleAuthorityMapper as an example mapper * show how to convert role names to upper case * document that the default prefix for that mapper maps role names properly Closes #19535 --- .../oidc/java/spring-security-adapter.adoc | 28 +++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/docs/documentation/securing_apps/topics/oidc/java/spring-security-adapter.adoc b/docs/documentation/securing_apps/topics/oidc/java/spring-security-adapter.adoc index c51aecc716..39af5b3489 100644 --- a/docs/documentation/securing_apps/topics/oidc/java/spring-security-adapter.adoc +++ b/docs/documentation/securing_apps/topics/oidc/java/spring-security-adapter.adoc @@ -194,8 +194,32 @@ Spring Security, when using role-based authentication, requires that role names For example, an administrator role must be declared in Keycloak as `ROLE_ADMIN` or similar, not simply `ADMIN`. The class `org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationProvider` supports an optional `org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper` which can be used to map roles coming from Keycloak to roles recognized by Spring Security. -Use, for example, `org.springframework.security.core.authority.mapping.SimpleAuthorityMapper` to insert the `ROLE_` prefix and convert the role name to upper case. -The class is part of Spring Security Core module. +Use, for example, `org.springframework.security.core.authority.mapping.SimpleAuthorityMapper`, which allows for case conversion and the addition of a prefix (which defaults to `ROLE_`). +The following code will convert the role names to upper case and, by default, add the `ROLE_` prefix to them: + +[source,java] +---- +@KeycloakConfiguration +public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter { + + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) { + auth.authenticationProvider(getKeycloakAuthenticationProvider()); + } + + private KeycloakAuthenticationProvider getKeycloakAuthenticationProvider() { + KeycloakAuthenticationProvider authenticationProvider = keycloakAuthenticationProvider(); + SimpleAuthorityMapper mapper = new SimpleAuthorityMapper(); + mapper.setConvertToUpperCase(true); + authenticationProvider.setGrantedAuthoritiesMapper(mapper); + + return authenticationProvider; + } + + ... +} + +---- ===== Client to Client Support