spring-security icon indicating copy to clipboard operation
spring-security copied to clipboard

Add hasScope as a valid SpEL expression to PreAuthorize

Open ngocnhan-tran1996 opened this issue 2 months ago • 2 comments

Closes: gh-18013

ngocnhan-tran1996 avatar Nov 08 '25 11:11 ngocnhan-tran1996

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 avatar Nov 21 '25 18:11 jzheaux

@jzheaux

I’ve made the requested changes. Let me know if anything else is needed.

ngocnhan-tran1996 avatar Nov 22 '25 05:11 ngocnhan-tran1996