Search code examples
javaspringspring-bootspring-securityspring-el

SpEL reference instance variable of class


I am using a custom method for my spring security pre authorize annotation and I need to pass a long list of perms in. I want to store that list externally because its used in a few places butI can't seem to figure out how to reference said list. It seems to always come through as null.

@RestController
@RequestMapping("/example")
public class MyController  {

...constructor/other stuff
public List<String> perms_I_want_to_reference = Arrays.asList("super","long","list")

@PreAuthorizze("@securityService.MyCustomMethod(principal, *this where I want to reference perms*)
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<?>doSomethingTopSecret(){
}

}

I have tried # and making list static and using T but so far nothing is working.


Solution

  • The only way to access your field from the annotation is via reflection. In order to do that Spring needs to have an access to the field of that class. I have not heard of a method to get a reference to the current class when the expression is being evaluated, but one way to do what you want is to reference a bean itself and access the field:

    public List<String> perms_I_want_to_reference = Arrays.asList("super","long","list");
    
    @PreAuthorizze("@securityService.MyCustomMethod(principal, @myController.perms_I_want_to_reference)")
    @RequestMapping(method = RequestMethod.GET)
    public ResponseEntity<?>doSomethingTopSecret(){ }