你能在Spring中为@PreAuthorize设置一个动态值吗?

ero*_*ppa 3 java spring spring-security spring-boot

现在我用

@PreAuthorize("hasAuthority('CREATE_USER_PRIVILEGE')")
Run Code Online (Sandbox Code Playgroud)

但我希望 CREATE_USER_PRIVILEGE 来自函数()。这可能吗?

Dan*_*ejo 11

你可以这样做:

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

}
Run Code Online (Sandbox Code Playgroud)