Repository navigation
Support transforming authorized scopes when the OAuth2Authorization object is created #1504
Description
Context
We have a use-case for filtering the scopes that go into an access_token, based on the Resource Owner's "roles" - e.g., if you have the role hr-user you can have payslip.view in the scopes of access tokens issued for you, but not the payslip.edit scope - even if the Client is allowed to request it.
There is no way to easily change the OAuth2Authorization#authorizedScopes() before it is created/saved.
The token itself, when it is a JWT, can be customized with an OAuth2TokenCustomizer<JwtEncodingContext> that acts on the scope claim, but the token response has the full list of authorized scopes.
Expected Behavior
When the OAuth2Authorization object is created and saved in the OAuth2Service, either through OAuth2AuthorizationCodeRequestAuthenticationProvider or OAuth2AuthorizationConsentAuthenticationProvider, I want to be able to alter the scopes.
Current workaround
Currently, we work around this by creating a custom AuthenticationProvider that wraps around both OAuth2AuthorizationCodeRequestAuthenticationProvider and OAuth2AuthorizationConsentAuthenticationProvider:
public class AppSsoAuthorizationCodeRequestAuthenticationProvider implements AuthenticationProvider {
// Either an OAuth2AuthorizationCodeRequestAuthenticationProvider or an OAuth2AuthorizationConsentAuthenticationProvider
private final AuthenticationProvider delegate;
private final OAuth2AuthorizationService authorizationService;
public AppSsoAuthorizationCodeRequestAuthenticationProvider(AuthenticationProvider delegate,
OAuth2AuthorizationService authorizationService) {
this.delegate = delegate;
this.authorizationService = authorizationService;
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
// This may throw an OAuth2AuthorizationCodeRequestAuthenticationException; in
// this case we rethrow.
var authResult = delegate.authenticate(authentication);
// This does not happen with our supported cases, but in the case of the device
// grant type, OAuth2AuthorizationConsentAuthenticationProvider will return null.
if (authResult == null) {
return null;
}
// When an authorization request comes in, and is valid, BUT the user is not
// authenticated, an OAuth2AuthorizationCodeRequestAuthenticationToken is
// returned, that is marked as !authenticated. This is a special case signaling
// that the end-user must log-in first. In this case, we just follow through.
//
// The rest of the filter chain will save the incoming request in the session and
// redirect the user to the login page. Once they are logged in, the saved request
// will be replayed.
if (!authResult.isAuthenticated()) {
return authResult;
}
// Sometimes the authentication flow returns a
// OAuth2AuthorizationConsentAuthenticationToken when consent is required.
// In that case, we just follow through. Otherwise we grab the result.
if (!(authResult instanceof OAuth2AuthorizationCodeRequestAuthenticationToken authCodeAuthResult)) {
return authResult;
}
// We load the authorization from the repo, change the scopes, and re-save it.
var authCode = authCodeAuthResult.getAuthorizationCode();
var authorization = authorizationService.findByToken(authCode.getTokenValue(),
new OAuth2TokenType(OAuth2ParameterNames.CODE));
// Filter the scopes based on the principal
var filteredScopes = filterScopes(authorization.getAuthorizedScopes(), authResult.getPrincipal());
var newAuthorization = OAuth2Authorization.from(authorization).authorizedScopes(filteredScopes).build();
authorizationService.save(newAuthorization);
//@formatter:off
return new OAuth2AuthorizationCodeRequestAuthenticationToken(
authCodeAuthResult.getAuthorizationUri(),
authCodeAuthResult.getClientId(),
authResultPrincipalAuthentication,
authCodeAuthResult.getAuthorizationCode(),
authCodeAuthResult.getRedirectUri(),
authCodeAuthResult.getState(),
filteredScopes
);
//@formatter:on
}
@Override
public boolean supports(Class<?> authentication) {
return delegate.supports(authentication);
}
private Set<String> filterScopes(Set<String> authorizedScopes, Object principal) {
// business logic
}
}
Activity
Suvink commentedon Feb 2, 2024
@Kehrlann How did you register
AppSsoAuthorizationCodeRequestAuthenticationProviderwith the authorization server?Kehrlann commentedon Feb 2, 2024
@Suvink excellent question, this is a classic pattern, but not 100% obvious. You register it with the
AuthorizationServerConfigurerusing an object post-processor. In your security configuration:Suvink commentedon Feb 7, 2024
Perfect. Initially we tried to register this with web security config but it didn't work. Then registered it with auth server configs and it works perfectly fine.
Thanks a lot for the support!
OrangeDog commentedon Apr 11, 2025
The intended way to wrap the providers is:
Another way to solve this problem may be to filter the requested scopes in a custom
AuthenticationConverter, but nothing will have been validated at that point.RazorNd commentedon Oct 4, 2025
Hi, I’ve been looking into this issue and I’d like to propose an API to address it.
Currently, we can customize the scope claim in the token via OAuth2TokenCustomizer, but we cannot influence the set of authorizedScopes that is stored inside OAuth2Authorization. This creates inconsistencies when filtering scopes based on user roles or policies.
Proposed API
Introduce a functional interface:
Default implementation would simply return the requested scopes unchanged:
Integration points
Call the filter right before building/updating OAuth2Authorization:
The filter’s return value becomes authorizedScopes() for the OAuth2Authorization.
Benefits
Example
Would this direction be acceptable for the project?
If so, I’d be happy to work on an initial implementation and open a PR
jgrandja commentedon Oct 8, 2025
@RazorNd Thanks for the suggestion. I'll take a look at this more closely after we release Spring Security 7.0 (Nov 17). There are higher priorities we are currently working on so this wouldn't make it into the next release.
RazorNd commentedon Jan 2, 2026
Hi @jgrandja, just wanted to follow up on my proposal from October regarding OAuth2ScopesAuthorizationFilter. Now that Spring Security 7.0 has been released, have you had a chance to review it? I’d be glad to help with an initial implementation or open a PR if you think this approach is suitable. Thanks for your time!
jgrandja commentedon Jan 5, 2026
@RazorNd I took a look at your proposed solution
OAuth2ScopesAuthorizationFilterand I feel the interface addresses a narrow purpose - only deals with scopes.As per the main issue description:
From a high-level design viewpoint, I believe the general abstraction here would be a Policy Decision. Having a general abstraction that allows for defining policies would provide a greater benefit since it could be used for different use cases, not just scope filtering. This would be my preference rather than introducing a new interface for a very specific use case.
Furthermore, based on the 2x upvotes in the main issue description, I do wonder if this issue even needs to be addressed at this time as we do have many other issues that have more demand.
Kehrlann commentedon Feb 5, 2026
@jgrandja I've had a new case for transforming the OAuth2Authorization object before creating it.
We perform additional actions during the authorization flow, and store the result in the authorization's pattern. In our case, we are fetching an OAuth2 token from an upstream authz server.
Our current workaround is to use the base
OAuth2AuthorizationCodeRequestAuthenticationProvider, then load theOAuth2Authorizationfrom the service, modify it and save it again.It'd be really nice to have a
Customizer<OAuth2Authorization.Builder>to modify the authorization in-place.OrangeDog commentedon Feb 5, 2026
In addition to changing the scopes during the confirm/consent step, I am also recording additional metadata from the initial request in the
OAuth2Authorization.Currently that's done in a custom
OAuth2AuthorizationService.save(), grabbing stuff fromRequestContextHolderif the attribute is missing. It's much less of a priority though, as it doesn't affect anything else, or need changing once first set, unlike scopes.jgrandja commentedon Feb 18, 2026
@Kehrlann
I believe
Customizer<OAuth2Authorization.Builder>would be limiting as I think we need to include additional context.For example, the following provide additonal context:
OAuth2AuthorizationCodeRequestAuthenticationProvider->Consumer<OAuth2AuthorizationCodeRequestAuthenticationContext> authenticationValidatorOAuth2AuthorizationConsentAuthenticationProvider->Consumer<OAuth2AuthorizationConsentAuthenticationContext> authorizationConsentCustomizerIdeally, we would define
Consumer<OAuth2_XXX_AuthenticationContext> authorizationCustomizerthat can be reused inOAuth2AuthorizationCodeRequestAuthenticationProviderandOAuth2AuthorizationConsentAuthenticationProvideror anyAuthenticationProviderthat callsOAuth2AuthorizationService.save().nikitanagar08 commentedon Mar 2, 2026
Hi, I'd like to work on this issue. I'll submit a draft PR with the implementation of the
OAuth2ScopesAuthorizationFilteras proposed by @RazorNd. Will follow the integration points outlined in the discussion.Add OAuth2AuthorizedScopesMapper for Client Credentials Grant
Add OAuth2AuthorizedScopesMapper for Client Credentials Grant
jgrandja commentedon Mar 3, 2026
@nikitanagar08 You might have missed this comment
Your PR introduces
OAuth2AuthorizedScopesMapper, which is not the enhancement we would be looking for. Please read the further comments. Also, at the moment, we are working on other higher priority items so our time is limited and I don't know if I have time to get to this in the current release cycle.Redesign: Add authorizationCustomizer pattern per maintainer feedback
Redesign: Add authorizationCustomizer pattern per maintainer feedback