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

现在我用

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

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


慕森卡
浏览 181回答 3
3回答

潇潇雨雨

你可以这样做:@RestControllerclass FooController {&nbsp; &nbsp; @PreAuthorize("hasAuthority(@securityService.privilege)")&nbsp; &nbsp; @GetMapping("/")&nbsp; &nbsp; public ResponseEntity<String> helloSecurity(@RequestParam("id") Integer id){&nbsp; &nbsp; &nbsp; &nbsp; return ResponseEntity.ok("Hello World");&nbsp; &nbsp; }}@Service("securityService")class SecurityService {&nbsp; &nbsp; public String getPrivilege(){&nbsp; &nbsp; &nbsp; &nbsp; return "CREATE_USER_PRIVILEGE";&nbsp; &nbsp; }}

繁星coding

基于上述解决方案,我实现了如下内容:@Controllerclass TestController {&nbsp; &nbsp; //calling a PreAuthorize on method level/ can be used on class level as well&nbsp; &nbsp; @PreAuthorize("hasAnyAuthority(@authorityService.authorities)")&nbsp; &nbsp; @RequestMapping("/application")&nbsp; &nbsp; public ModelAndView newPage() throws{&nbsp; &nbsp; &nbsp; &nbsp; return new ModelAndView(view);&nbsp; &nbsp;}&nbsp; &nbsp;}@Service("authorityService")class AuthorityService{&nbsp; &nbsp; @Value("${app.authorities}") // read roles from properties file&nbsp; &nbsp; private String authorities;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; public List<String> getAuthorities(){&nbsp; &nbsp; &nbsp; &nbsp; // convert the comma separated Strings to list.&nbsp; &nbsp; &nbsp; &nbsp; List<String> items = Arrays.asList(authorities.split("\\s*,\\s*"));&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; return items;&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;}

波斯汪

您必须首先使用构造函数或注释自动装配您的服务,然后您可以使用 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}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java