使用Spring安全过滤器锁定除少数路线之外的所有内容

2022-09-03 09:43:55

我们正在重新设计我们的产品,以删除SpringSecurity中默认的“匿名用户”行为,并希望锁定所有URL(通过过滤器安全性),除了几个端点。我们无法弄清楚的是如何指定“锁定除X,Y和Z之外的所有内容”

我们的安全设置基本上可以归结为以下内容:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // disable anonymous users
            .anonymous().disable()

            // don't add ROLE_ to the role...
            .authorizeRequests()
                .regexMatchers("^/", "^/login", "^/mobile/login", "^/api/auth/.*")
                    .authenticated()
                .and()  
        ;
    }
}

我采取的其他路线类似于:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // disable anonymous users
            .anonymous().disable()

            // don't add ROLE_ to the role...
            .authorizeRequests()
            .antMatchers("/**")
                .authenticated()
            .antMatchers("/", "/login", "/mobile/login", "/api/auth/**", "/reservations/**")
                .permitAll()
            .and()
        ;
    }
}

任何建议/意见将不胜感激。

谢谢!


答案 1

我们正在重新设计我们的产品,以删除Spring Security中默认的“匿名用户”行为

我想知道你这是什么意思。根据描述的其余部分,我认为您不需要以下内容(即您应该将其删除):

anonymous().disabled()

上面说,如果没有用户经过身份验证,用户将会,这往往会导致s。nullNullPointerException

请记住,对于(或)订购很重要。您拥有的 Java 配置(为了便于阅读,稍微重新格式化了一下)authorizeRequests()<intercept-url>)

.authorizeRequests()
    .antMatchers("/**").authenticated()
    .antMatchers("/", "/login", "/mobile/login", "/api/auth/**", "/reservations/**").permitAll()
    .and()

将使用以下逻辑:

  • 此请求是否与“/**”匹配?
    • 是的,所有内容都与“/**”匹配。因此,每个请求都要求对用户进行身份验证。
  • 忽略所有其他规则,因为我们已经匹配

相反,您应该使用以下内容:

.authorizeRequests()
    .antMatchers("/", "/login", "/mobile/login", "/api/auth/**", "/reservations/**").permitAll()
    .anyRequest().authenticated()
    .and()
  • 请求是否匹配“/”或“/login”或...?
    • 如果是,则允许任何人访问它并停止(不再使用规则)。
    • 如果请求不匹配,请继续。
  • 请求是否与任何请求匹配?
    • 是的,因此,如果请求与以前的规则不匹配,则它将要求对用户进行身份验证。

注意:更简洁地表示为 。antMatchers("/**")anyRequest()


答案 2

Rob Winch的答案在几乎所有情况下都是正确的答案,也是我在项目中采用的方法。我确实认为还值得注意的是,另一种可能的方法可能是执行以下操作:

public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/assets/**", "/index.html");
}

请注意,这是与您之前提交的示例中的方法不同的方法。该方法具有类型的参数,而此方法具有 类型 。HttpSecurityWebSecurity

此代码示例将执行的操作是查找匹配的任何请求,并完全跳过 HTTP 安全筛选器。

因此,如果您想优化一些您知道需要零功能的请求,那么这可能是一个很好的解决方案。这意味着,如果您使用 , 等功能,它们将不会应用于上述示例中的匹配请求(“/assets/**”,“/index.html”)HttpSecuritycsrf()requestCache()headers()


推荐