显式保护特定模式而不是忽略所有非安全模式

时间:2015-03-29 10:42:30

标签: spring-security

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

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

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

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

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

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

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

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

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

1 个答案:

答案 0 :(得分:2)

忽略安全性(即使对于公共静态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);
相关问题