-
Notifications
You must be signed in to change notification settings - Fork 220
feat(spring): add opt-in Keycloak role mapping to VaadinSecurityConfigurer #25627
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
totally-not-ai
wants to merge
10
commits into
main
Choose a base branch
from
feat/keycloak-role-mapping
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+724
−0
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
474ba33
test: specify Keycloak realm and client role mapping
totally-not-ai[bot] b858fd0
feat(spring): add opt-in Keycloak role mapping to VaadinSecurityConfi…
totally-not-ai[bot] 1bd52c7
fix(spring): keep the userinfo claims when mapping Keycloak roles
totally-not-ai[bot] a0d32a6
chore: restore the unrelated flow-client lockfile change
totally-not-ai[bot] b948240
fix(spring): keep VaadinSecurityConfigurer usable without oauth2-client
totally-not-ai[bot] dab7a97
Merge branch 'main' into feat/keycloak-role-mapping
Artur- 93b3ec3
refactor(spring): simplify the Keycloak role mapping wiring
totally-not-ai[bot] 8989a5d
fix(spring): cache the absence of a Keycloak access token decoder
totally-not-ai[bot] 6ce6fd0
Merge remote-tracking branch 'origin/main' into feat/keycloak-role-ma…
totally-not-ai[bot] 451e58a
chore: restore the copyright years of the unrelated CDI test sources
totally-not-ai[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
258 changes: 258 additions & 0 deletions
258
vaadin-spring/src/main/java/com/vaadin/flow/spring/security/KeycloakOidcUserMapper.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,258 @@ | ||
| /* | ||
| * Copyright 2000-2026 Vaadin Ltd. | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); you may not | ||
| * use this file except in compliance with the License. You may obtain a copy of | ||
| * the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT | ||
| * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the | ||
| * License for the specific language governing permissions and limitations under | ||
| * the License. | ||
| */ | ||
| package com.vaadin.flow.spring.security; | ||
|
|
||
| import java.util.Collections; | ||
| import java.util.LinkedHashSet; | ||
| import java.util.List; | ||
| import java.util.Map; | ||
| import java.util.Optional; | ||
| import java.util.Set; | ||
| import java.util.concurrent.ConcurrentHashMap; | ||
| import java.util.function.Supplier; | ||
| import java.util.stream.Stream; | ||
|
|
||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
| import org.springframework.core.convert.converter.Converter; | ||
| import org.springframework.security.core.GrantedAuthority; | ||
| import org.springframework.security.core.authority.SimpleGrantedAuthority; | ||
| import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserService; | ||
| import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserSource; | ||
| import org.springframework.security.oauth2.client.registration.ClientRegistration; | ||
| import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser; | ||
| import org.springframework.security.oauth2.core.oidc.user.OidcUser; | ||
| import org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority; | ||
| import org.springframework.security.oauth2.jwt.Jwt; | ||
| import org.springframework.security.oauth2.jwt.JwtDecoder; | ||
| import org.springframework.security.oauth2.jwt.JwtDecoderFactory; | ||
| import org.springframework.security.oauth2.jwt.JwtException; | ||
| import org.springframework.security.oauth2.jwt.JwtValidators; | ||
| import org.springframework.security.oauth2.jwt.NimbusJwtDecoder; | ||
| import org.springframework.util.StringUtils; | ||
|
|
||
| /** | ||
| * Maps Keycloak realm and client roles to Spring Security granted authorities. | ||
| * <p> | ||
| * Keycloak puts the roles of a user into the access token rather than into the | ||
| * ID token, so they are not part of the {@link OidcUser} that | ||
| * {@link OidcUserService} builds by default. This converter decodes the access | ||
| * token and adds | ||
| * <ul> | ||
| * <li>the realm roles from the {@code realm_access} claim,</li> | ||
| * <li>the roles that the {@code resource_access} claim grants for the client id | ||
| * of the current client registration, and</li> | ||
| * <li>the scopes of the access token, prefixed with {@code SCOPE_}.</li> | ||
| * </ul> | ||
| * Realm and client roles both become role authorities, using the role prefix of | ||
| * the application ({@code ROLE_} unless a | ||
| * {@link org.springframework.security.config.core.GrantedAuthorityDefaults} | ||
| * bean says otherwise), so that {@code @RolesAllowed("admin")} and | ||
| * {@code hasRole("admin")} match a Keycloak role named {@code admin}. Roles | ||
| * that {@code resource_access} grants for other clients are ignored. | ||
| * <p> | ||
| * An access token that is not a JWT, or that this application is not allowed to | ||
| * decode, is not an error: the user is mapped without any role authorities, as | ||
| * the default {@link OidcUserService} would do. | ||
| * <p> | ||
| * The recommended way to use this converter is | ||
| * {@link VaadinSecurityConfigurer#keycloakRoleMapping()}, which installs it for | ||
| * a single security filter chain. Applications that build their own | ||
| * {@link OidcUserService} can install it directly: | ||
| * | ||
| * <pre> | ||
| * <code> | ||
| * var oidcUserService = new OidcUserService(); | ||
| * oidcUserService.setOidcUserConverter(new KeycloakOidcUserMapper()); | ||
| * </code> | ||
| * </pre> | ||
| * | ||
| * @author Vaadin Ltd | ||
| * @since 25.4 | ||
| */ | ||
| public class KeycloakOidcUserMapper | ||
| implements Converter<OidcUserSource, OidcUser> { | ||
|
|
||
| private static final Logger LOGGER = LoggerFactory | ||
| .getLogger(KeycloakOidcUserMapper.class); | ||
|
|
||
| private static final String REALM_ACCESS_CLAIM = "realm_access"; | ||
|
|
||
| private static final String RESOURCE_ACCESS_CLAIM = "resource_access"; | ||
|
|
||
| private static final String ROLES_CLAIM = "roles"; | ||
|
|
||
| private static final String DEFAULT_ROLE_PREFIX = "ROLE_"; | ||
|
|
||
| private static final String SCOPE_PREFIX = "SCOPE_"; | ||
|
|
||
| private final Supplier<String> rolePrefix; | ||
|
|
||
| private final JwtDecoderFactory<ClientRegistration> decoderFactory; | ||
|
|
||
| /** | ||
| * Decoders by registration id, empty for a registration that has no | ||
| * decoder, so that one is not built again on every login. | ||
| */ | ||
| private final Map<String, Optional<JwtDecoder>> decoders = new ConcurrentHashMap<>(); | ||
|
|
||
| /** | ||
| * Creates a mapper that prefixes roles with {@code ROLE_}. | ||
| */ | ||
| public KeycloakOidcUserMapper() { | ||
| this(() -> null, KeycloakOidcUserMapper::createDecoder); | ||
| } | ||
|
|
||
| /** | ||
| * Creates a mapper that prefixes roles with the given prefix. | ||
| * | ||
| * @param rolePrefix | ||
| * the prefix to add to a Keycloak role name, or {@code null} to | ||
| * use {@code ROLE_} | ||
| */ | ||
| public KeycloakOidcUserMapper(String rolePrefix) { | ||
| this(() -> rolePrefix, KeycloakOidcUserMapper::createDecoder); | ||
| } | ||
|
|
||
| /** | ||
| * Creates a mapper that looks up the role prefix when it maps a user, for a | ||
| * caller that only knows the prefix once the security filter chain has been | ||
| * configured. | ||
| * | ||
| * @param rolePrefix | ||
| * supplies the prefix to add to a Keycloak role name, may supply | ||
| * {@code null} to use {@code ROLE_} | ||
| */ | ||
| KeycloakOidcUserMapper(Supplier<String> rolePrefix) { | ||
| this(rolePrefix, KeycloakOidcUserMapper::createDecoder); | ||
| } | ||
|
|
||
| KeycloakOidcUserMapper(Supplier<String> rolePrefix, | ||
| JwtDecoderFactory<ClientRegistration> decoderFactory) { | ||
| this.rolePrefix = rolePrefix != null ? rolePrefix : () -> null; | ||
| this.decoderFactory = decoderFactory; | ||
| } | ||
|
|
||
| @Override | ||
| public OidcUser convert(OidcUserSource userSource) { | ||
| var userRequest = userSource.getUserRequest(); | ||
| var userInfo = userSource.getUserInfo(); | ||
| var idToken = userRequest.getIdToken(); | ||
| var accessToken = userRequest.getAccessToken(); | ||
| var clientRegistration = userRequest.getClientRegistration(); | ||
| var authorities = new LinkedHashSet<GrantedAuthority>(); | ||
| accessToken.getScopes().stream() | ||
| .map(scope -> new SimpleGrantedAuthority(SCOPE_PREFIX + scope)) | ||
| .forEach(authorities::add); | ||
| decodeAccessToken(clientRegistration, accessToken.getTokenValue()) | ||
| .ifPresent(jwt -> collectRoles(jwt, | ||
| clientRegistration.getClientId(), authorities)); | ||
| var userNameAttributeName = clientRegistration.getProviderDetails() | ||
| .getUserInfoEndpoint().getUserNameAttributeName(); | ||
| if (StringUtils.hasText(userNameAttributeName)) { | ||
| authorities.add(new OidcUserAuthority(idToken, userInfo, | ||
| userNameAttributeName)); | ||
| return new DefaultOidcUser(authorities, idToken, userInfo, | ||
| userNameAttributeName); | ||
| } | ||
| authorities.add(new OidcUserAuthority(idToken, userInfo)); | ||
| return new DefaultOidcUser(authorities, idToken, userInfo); | ||
| } | ||
|
|
||
| private void collectRoles(Jwt accessToken, String clientId, | ||
| Set<GrantedAuthority> authorities) { | ||
| var claims = accessToken.getClaims(); | ||
| var resourceAccess = asMap(claims.get(RESOURCE_ACCESS_CLAIM)); | ||
| Stream.of(asMap(claims.get(REALM_ACCESS_CLAIM)), | ||
| asMap(resourceAccess.get(clientId))) | ||
| .flatMap(access -> extractRoles(access).stream()) | ||
| .map(this::toRoleAuthority).forEach(authorities::add); | ||
| } | ||
|
|
||
| /** | ||
| * Decodes the access token with the decoder of the given client | ||
| * registration, which is created on first use and then reused. | ||
| */ | ||
| private Optional<Jwt> decodeAccessToken(ClientRegistration registration, | ||
| String tokenValue) { | ||
| var decoder = decoders.computeIfAbsent(registration.getRegistrationId(), | ||
| id -> Optional.ofNullable( | ||
| decoderFactory.createDecoder(registration))); | ||
| if (decoder.isEmpty()) { | ||
| LOGGER.debug( | ||
| "Client registration '{}' has no JWK set URI, so its access " | ||
| + "token cannot be decoded and no Keycloak roles " | ||
| + "are mapped for it", | ||
| registration.getRegistrationId()); | ||
| return Optional.empty(); | ||
| } | ||
| try { | ||
| return Optional.of(decoder.get().decode(tokenValue)); | ||
| } catch (JwtException e) { | ||
| LOGGER.debug( | ||
| "The access token of client registration '{}' could not be " | ||
| + "decoded as a JWT, so no Keycloak roles are " | ||
| + "mapped for it", | ||
| registration.getRegistrationId(), e); | ||
| return Optional.empty(); | ||
| } | ||
| } | ||
|
|
||
| private GrantedAuthority toRoleAuthority(String role) { | ||
| return new SimpleGrantedAuthority(rolePrefix() + role); | ||
| } | ||
|
|
||
| /** | ||
| * Returns the role prefix in use, resolved on every call so that a prefix | ||
| * that is only known once the security filter chain is fully configured is | ||
| * picked up. | ||
| */ | ||
| String rolePrefix() { | ||
| var prefix = rolePrefix.get(); | ||
| return prefix != null ? prefix : DEFAULT_ROLE_PREFIX; | ||
| } | ||
|
|
||
| @SuppressWarnings("unchecked") | ||
| private static List<String> extractRoles(Map<String, Object> access) { | ||
| var roles = access.get(ROLES_CLAIM); | ||
| return roles instanceof List<?> ? (List<String>) roles : List.of(); | ||
| } | ||
|
|
||
| @SuppressWarnings("unchecked") | ||
| private static Map<String, Object> asMap(Object value) { | ||
| return value instanceof Map<?, ?> map ? (Map<String, Object>) map | ||
| : Collections.emptyMap(); | ||
| } | ||
|
|
||
| /** | ||
| * Creates a decoder for the access tokens of the given client registration, | ||
| * or {@code null} when the registration has no JWK set URI to verify them | ||
| * against. | ||
| */ | ||
| private static JwtDecoder createDecoder(ClientRegistration registration) { | ||
| var providerDetails = registration.getProviderDetails(); | ||
| var jwkSetUri = providerDetails.getJwkSetUri(); | ||
| if (!StringUtils.hasText(jwkSetUri)) { | ||
| return null; | ||
| } | ||
| var issuerUri = providerDetails.getIssuerUri(); | ||
| var decoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build(); | ||
| decoder.setJwtValidator(StringUtils.hasText(issuerUri) | ||
| ? JwtValidators.createDefaultWithIssuer(issuerUri) | ||
| : JwtValidators.createDefault()); | ||
| return decoder; | ||
| } | ||
| } |
67 changes: 67 additions & 0 deletions
67
vaadin-spring/src/main/java/com/vaadin/flow/spring/security/KeycloakRoleMapping.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,67 @@ | ||
| /* | ||
| * Copyright 2000-2026 Vaadin Ltd. | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); you may not | ||
| * use this file except in compliance with the License. You may obtain a copy of | ||
| * the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT | ||
| * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the | ||
| * License for the specific language governing permissions and limitations under | ||
| * the License. | ||
| */ | ||
| package com.vaadin.flow.spring.security; | ||
|
|
||
| import java.util.function.Supplier; | ||
|
|
||
| import org.springframework.security.config.annotation.web.builders.HttpSecurity; | ||
| import org.springframework.security.config.annotation.web.configurers.oauth2.client.OAuth2LoginConfigurer; | ||
| import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserService; | ||
|
|
||
| /** | ||
| * Makes an OAuth2 login use an {@link OidcUserService} that maps Keycloak roles | ||
| * with {@link KeycloakOidcUserMapper}. | ||
| * <p> | ||
| * This lives apart from {@link VaadinSecurityConfigurer} on purpose. The | ||
| * {@code spring-security-oauth2-client} dependency that {@link OidcUserService} | ||
| * comes from is optional, and passing an {@code OidcUserService} to a parameter | ||
| * of type {@code OAuth2UserService} makes the verifier load the latter to check | ||
| * assignability. Doing that from {@code VaadinSecurityConfigurer} would break | ||
| * every application that configures Vaadin security without the dependency, | ||
| * because a class is verified as a whole when it is loaded. Keeping it here | ||
| * means the class is only loaded by an application that asks for Keycloak role | ||
| * mapping, which has the dependency anyway. | ||
| * | ||
| * @see VaadinSecurityConfigurer#keycloakRoleMapping() | ||
| */ | ||
| final class KeycloakRoleMapping { | ||
|
|
||
| private KeycloakRoleMapping() { | ||
| // Only static utility methods | ||
| } | ||
|
|
||
| /** | ||
| * Sets an {@link OidcUserService} that maps Keycloak roles on the given | ||
| * OAuth2 login, and shares it so that it can be inspected or replaced. | ||
| * | ||
| * @param loginConfigurer | ||
| * the OAuth2 login configurer to customize | ||
| * @param http | ||
| * the security builder to share the service with | ||
| * @param rolePrefix | ||
| * supplies the role prefix to use, resolved when a user is | ||
| * mapped | ||
| */ | ||
| static void apply(OAuth2LoginConfigurer<HttpSecurity> loginConfigurer, | ||
| HttpSecurity http, Supplier<String> rolePrefix) { | ||
| var oidcUserService = new OidcUserService(); | ||
| oidcUserService | ||
| .setOidcUserConverter(new KeycloakOidcUserMapper(rolePrefix)); | ||
| http.setSharedObject(OidcUserService.class, oidcUserService); | ||
| loginConfigurer.userInfoEndpoint(userInfoEndpoint -> userInfoEndpoint | ||
| .oidcUserService(oidcUserService)); | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.