我有以下示例:
任何 Controller :
@Controller
@RequestMapping(value = "api/whatever")
public class WhateverController {
@Autowired private WhateverService whateverService;
@RequestMapping(value = "/list", method = GET)
@Secured({ "ROLE_WHATEVER_CANSEARCH" })
@ResponseBody
public List<WhateverDTO> findList(@RequestParam(value = "values") String[] values) {
return whateverService.findThings(values);
}
}
任何服务:
@Service
public class WhateverService {
@Autowired private WhateverDAO whateverDAO;
public List<WhateverDTO> findThings(String[] values) {
//...
validate();
return whateverDAO.findThings(values);
}
@Secured({ "ROLE_SPECIFICPERMISSION" }) // Throws AccessDeniedException
private void validate() {
if(thing) throw new RuntimeException("You can't...");
}
}
- 注释@Secured 是否可以在“WhateverService”的“验证”方法中起作用?
- 如果不会,那是为什么?
- 同样的行为适用于注解@PreAuthorize?
最佳答案
不,不是因为它是私有(private)的,而是因为Spring-Security是基于Spring-AOP的。 在Spring-AOP上,同一个类中的方法之间的调用不会调用切面。
使用@Secured 注释,在方法之前进行测试。如果用户没有正确的角色,则会抛出异常。
@PreAuthorize 实际上是一样的,除了它允许更高级的行为。
您还可以使用 WebSecurityConfigurerAdapter 配置安全性。
并且不要忘记使用 @EnableGlobalMethodSecurity(prePostEnabled = true)
关于java - @Secured 和@PreAuthorize 注解在哪些方法中起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51421785/