您可以在Spring中将动态值设置为@PreAuthorize吗?

时间:2019-10-18 22:25:57

标签: java spring spring-boot spring-security

现在我使用

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

但是我希望CREATE_USER_PRIVILEGE来自function()。这可能吗?

3 个答案:

答案 0 :(得分:2)

您可以执行以下操作:

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

}

答案 1 :(得分:0)

基于this great article

您首先必须使用构造函数或批注自动连接服务,然后可以使用Spel语言来使用它,如下面的示例所述

@RequestMapping(value="/id/{domainObjectId}/dostuff", method=RequestMethod.POST, produces="application/json")
@PreAuthorize(value="hasRole('ROLE_DomainObjectAdmin') or @domainObjectServiceImpl.findDomainObject(#domainObjectId).getOwners().contains(#userAccount.getEmployee())")
public String setObjectiveComplete(@PathVariable String domainObjectId, UserAccount userAccount) {
// Do stuff
}

答案 2 :(得分:0)

基于上述解决方案,我实现了如下内容:

@Controller
class TestController {

    //calling a PreAuthorize on method level/ can be used on class level as well
    @PreAuthorize("hasAnyAuthority(@authorityService.authorities)")
    @RequestMapping("/application")
    public ModelAndView newPage() throws{
        return new ModelAndView(view);
   }
   
}

@Service("authorityService")
class AuthorityService{

    @Value("${app.authorities}") // read roles from properties file
    private String authorities;
    
    public List<String> getAuthorities(){
        // convert the comma separated Strings to list.
        List<String> items = Arrays.asList(authorities.split("\\s*,\\s*")); 
        return items;
    }
    
}