Search code examples
javaspringspring-bootspring-security

Spring security expression based access control - referencing beans


I'm attempting to use expression based access control in Spring security by referencing a bean method in my web security expression. So for example I have something like this

@Component
public class AuthorizationChecker {
    public boolean check(Authentication authentication, HttpServletRequest request) {
        return true;
    }
}

And then security configure method like this

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().and().anonymous().disable().authorizeRequests().antMatchers(HttpMethod.POST, "/**")
            .access("@authorizationChecker(authentication, request)").and().oauth2ResourceServer().jwt();
}

However when starting the Spring Boot application I get Parsing exception. Digging through the Spring code I can see it fails parsing with the following message

EL1041E: After parsing a valid expression, there is still more data in the expression: 'lparen(()'

Any ideas? As far as I can see it matches the syntax given in the Spring Security documentation.

https://docs.spring.io/spring-security/reference/5.7/servlet/authorization/expression-based.html#el-access-web-beans


Solution

  • You should try this, note the explicit call of the check method:

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and()
            .anonymous().disable()
            .authorizeRequests().antMatchers(HttpMethod.POST, "/**")
                .access("@authorizationChecker.check(authentication, request)")
            .and().oauth2ResourceServer().jwt();
    }