spring-security
spring-security copied to clipboard
Add hasScope as a valid SpEL expression to PreAuthorize
Closes: gh-18013
Hi, @ngocnhan-tran1996. We want to be careful about adding to the expression root, especially now that it has implications for AuthorizationManagerFactory. Alternatively, we could consider an interface OAuth2AuthorizationManagerFactory like this:
public interface OAuth2AuthorizationManagerFactory<T> {
default AuthorizationManager<T> hasScope(String scope) {
return OAuth2AuthorizationManagers.hasScope(scope);
}
// ...
}
And a default implementation:
@Bean
OAuth2AuthorizationManagerFactory<Object> oauth2() {
return new DefaultOAuth2AuthorizationManagerFactory();
}
That takes an AuthorizationManagerFactory as a parameter in support of MFA:
@Bean
OAuth2AuthorizationManagerFactory<Object> oauth2(AuthorizationManagerFactory<Object> mfa) {
return new OAuth2AuthorizationManagerFactory(mfa);
}
And then do:
@PreAuthorize("@oauth2.hasScope('message:read')")
I like this pattern since it allows for other modules to add their own expressions as well, without needing to change or extend SecurityExpressionRoot.
@jzheaux
I’ve made the requested changes. Let me know if anything else is needed.