目前我试图弄清楚 Spring Security 如何评估给定的 URL、表达式和注释。到目前为止,它似乎总是首先检查 security-context.xml
中的条目。如果这是一个 denyAll
,它将停止进一步处理请求。
也许我忘记设置一些配置选项,但是(在我看来)不可能使用 Spring Security 的注释(如 @Secured
、@PermitAll
)构建一个漂亮的白名单> 等)。
我想要的基本上是注释 @Controller
内的方法以允许访问。例如:
@Controller
@RequestMapping("/test")
public MyController {
@RequestMapping("")
public void tryToGetSomething() {
// no security annotation -> denyAll
}
@RequestMapping("/public")
@PermitAll
public void tryToGetSomethingPublic() {
// this will always have access allowed
}
@RequestMapping("/admin")
@Secured({"ROLE_ADMIN"})
public void tryToGetSomethingReallyImportant() {
// this can only be accessed by admins
}
}
采用这种方法的主要原因是:安全;-)
。在编写代码时总是可能会忘记一些注释。而且通过这种方法,这样的错误不会影响敏感数据的安全。
所以我的问题是:我怎样才能实现这一目标?
最佳答案
您可以尝试将安全切入点与注释结合使用:
<global-method-security pre-post-annotations="enabled">
<!-- Disable access to all controller methods -->
<protect-pointcut expression="execution(* com.mycompany.controllers.*Controller.*(..))"
access="ROLE_THAT_DOES_NOT_EXIST"/>
</global-method-security>
@Controller
@RequestMapping("/test")
public MyController {
@RequestMapping("")
public void tryToGetSomething() {
// pointcut rule -> no one has ROLE_THAT_DOES_NOT_EXIST -> no one can call this code
}
@RequestMapping("/public")
@PreAuthorized("permitAll")
public void tryToGetSomethingPublic() {
// annotations take precedence over pointcuts, so anyone can call this code due to @PreAuthorized("permitAll") rule
}
}
参见corresponding entry来自官方文档。也许您可以使用 denyAll
而不是 ROLE_THAT_DOES_NOT_EXIST
。
希望这有帮助。
关于使用注释和全局拒绝的 Spring Security 白名单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17689247/