Skip to content
Advertisement

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?

Advertisement

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";
    }

}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement