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

Spring security 显式保护特定模式,而不是忽略所有非安全模式,spring-security,Spring Security,我有一个只需要保护/admin/page的应用程序。所有其他页面都没有需要安全性的登录、帐户或其他功能 根据其他问题和教程,我目前已经通过显式忽略所有不需要安全性的路径实现了这一点,例如 web .忽略() .antMatchers(“/js/**”); 网状物 .忽略() .antMatchers(“/static/**”); 网状物 .忽略() .antMatchers(“/images/**”); 网状物 .忽略() .antMatchers(“/css/**”); 网状物 .忽略() .

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

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

web
.忽略()
.antMatchers(“/js/**”);
网状物
.忽略()
.antMatchers(“/static/**”);
网状物
.忽略()
.antMatchers(“/images/**”);
网状物
.忽略()
.antMatchers(“/css/**”);
网状物
.忽略()
.antMatchers(“/fonts/**”);
这会使配置更大,并且不完全清楚您要保护什么,因为它只说明异常

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

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

考虑到这一点,我们将删除您拥有的忽略配置,只需更新您的安全授权规则。例如:

@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);