使用注释和全局拒绝的 Spring Security 白名单方法

标签 spring spring-mvc spring-security annotations whitelist

目前我试图弄清楚 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/

相关文章:

spring - Mongodb upsert 抛出 DuplicateKeyException

java - org.springframework.beans.factory.BeanCreationException : Error creating bean with name 'sessionFactory' defined in ServletContexoller':

java - 如何在多 Gradle 项目的 JUnit Spring 上下文中加载资源属性?

java - 在 XSLT 中使用 spring 标签

java - 从 spring multiple <form :select> 绑定(bind)对象

java - 在 API 请求上使用附加 header 参数跳过 Oauth 2.0 授权 - Spring Security

java - 为什么 Spring 将实例初始化为单例?有哪些原因影响了他们决定以这种方式处理初始化?

java - spring boot eclipse jre/jdk警告

java - Spring boot能否根据property文件的内容动态创建端点?

grails - 如何有条件地跳过 Grails Spring Security 插件过滤器链中的 SecurityContextPersistenceFilter 过滤器