Can you set a dynamic value to @PreAuthorize in Spring?



Right now I use

@PreAuthorize("hasAuthority('CREATE_USER_PRIVILEGE')")

But I want the CREATE_USER_PRIVILEGE to come from a function(). Is this possible?

Answer

You could do something like this:

@RestController
class FooController {

    @PreAuthorize("hasAuthority(@securityService.privilege)")
    @GetMapping("/")
    public ResponseEntity<String> helloSecurity(@RequestParam("id") Integer id){
        return ResponseEntity.ok("Hello World");
    }


}

@Service("securityService")
class SecurityService {

    public String getPrivilege(){
        return "CREATE_USER_PRIVILEGE";
    }

}


Source: stackoverflow