【问题标题】:Explicitly secure a specific pattern instead of ignoring all non-secured patterns显式保护特定模式,而不是忽略所有非安全模式
【发布时间】:2015-06-02 09:37:00
【问题描述】:

我有一个应用程序,我只需要保护 /admin/ 页面。所有其他页面都没有登录、帐户或其他需要安全性的功能。

根据其他问题和教程,我目前已经通过明确忽略所有不需要安全性的路径来实现这一点,例如

        web
                .ignoring()
                .antMatchers("/js/**");

        web
                .ignoring()
                .antMatchers("/static/**");

        web
                .ignoring()
                .antMatchers("/images/**");

        web
                .ignoring()
                .antMatchers("/css/**");

        web
                .ignoring()
                .antMatchers("/fonts/**");

这会使配置变得更大,并且不完全清楚您要保护的内容,因为它只说明了例外情况。

有没有办法先明确禁用所有安全性,然后添加要激活的模式?

【问题讨论】:

    标签: spring-security


    【解决方案1】:

    忽略安全性(即使对于公共静态 URL)通常被认为是不好的做法,除非您有明确的理由这样做。请记住,Spring Security 还可以通过 Security HTTP Response Headers 等方式帮助确保您的应用程序安全。

    考虑到这一点,将删除您拥有的忽略配置并简单地更新您的安全授权规则。例如:

    @Configuration
    @EnableWebMvcSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .authorizeRequests()
                    .antMatchers("/admin/").hasRole("ADMIN")
                    .and()
                .formLogin()
                    ...
        }
    
        // ...
    }
    

    也就是说,如果您确实需要忽略除以 admin 开头的请求之外的所有请求,您可以使用正则表达式轻松执行此操作:

    web
        .ignoring()
            .regexMatchers("^(?!/admin/).*");
    

    您还可以注入自定义匹配器实现。 Spring Security 甚至提供了以下开箱即用的功能:

    RequestMatcher adminRequests = new AntPathRequestMatcher("/admin/**");
    RequestMatcher notAdminRequests = new NegatedRequestMatcher(adminRequests);
    web
        .ignoring()
            .requestMatchers(notAdminRequests);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-16
      • 1970-01-01
      相关资源
      最近更新 更多