@PreAuthorize with Bean in expression (Spring Boot)

4k Views Asked by At

Simple question, I got a @Service class @Autowired up in my controller.

Trying to put a little security on one of the methods in my controller. So for simplicity I did this to test

@PreAuthorize("@myService.helloThere()")
public void someControllerMethod() {
    ...
}

But no success really. Getting an exception during method call.

java.lang.IllegalArgumentException: Failed to evaluate expression '@myService.helloThere()'

Am I missing something with EL here?

Update

Just adding the last Caused by exception

Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1057E:(pos 1): No bean resolver registered in the context to resolve access to bean 'dummyServiceImpl'

Now I don't understand why it wouldn't be accesible in the StandardEvaluationContext if I'm using @Autowired ?

Update 2

Since I had my own Role Hierarchy hooked up in a custom GlobalMethodSecurityConfiguration extended class, the DefaultMethodSecurityExpressionHandler did not have the applicationContext set by default. I'm not sure why this is by design or I was missing something obvious. I searched the reference pages and found another SO thread that helped me solve the problem. I'm posting the updated security configuration.

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class GlobalMethodSecurityConfig extends GlobalMethodSecurityConfiguration {

    @Autowired
    ApplicationContext applicationContext; //added this

    @Override
    protected MethodSecurityExpressionHandler createExpressionHandler() {           
        final DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler();

        handler.setApplicationContext(applicationContext); //added this
        RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();

        roleHierarchy.setHierarchy("ROLE_ADMIN > ROLE_USER_MANAGER > ROLE_USER");
        handler.setRoleHierarchy(roleHierarchy);
        return handler;
    }
}
1

There are 1 best solutions below

1
Shankar On

Try this.

@PreAuthorize("myService.helloThere()")