簡體   English   中英

您可以在 Spring 中為 @PreAuthorize 設置動態值嗎?

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

現在我用

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

但我希望 CREATE_USER_PRIVILEGE 來自函數()。 這可能嗎?

你可以這樣做:

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

}

基於這篇很棒的文章

您必須首先使用構造函數或注釋自動裝配您的服務,然后您可以使用 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
}

基於上述解決方案,我實現了這樣的東西:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM