首页 > 解决方案 > Spring security ignore url 不适用于 we security ignore 方法

问题描述

我们正面临 SpringSecurity 忽略方法的问题。我们尝试跳过一些 url(执行器/健康)和资源的身份验证。身份验证在外部进行,我们有一个自定义过滤器来提取授权原则。

我们重写配置的方法,如下所示:

public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/**", "/actuator/health");
}
protected void configure(HttpSecurity http) throws Exception {
         http.addFilter(cutstomFilter).authorizeRequests()
        .antMatchers("/add","/update","/upload").hasAuthority("ADMIN").anyRequest().authenticated()
        .and().logout().logoutSuccessUrl("/logoutUser").and()
        .exceptionHandling().accessDeniedPage("/accessDenied").and().csrf().disable();
    }

通过给定的实现,我们的 customFilter 被调用来获取资源和健康 url。由于原则更改,这导致重新验证。

我们尝试添加此代码,但 customFilter 也被称为健康 url。

http.authorizeRequests().antMatchers("/actuator/health").permitAll() 

注意:检查了@Rob Winch 答案,但不明白如果我们将这些 url 放入忽略列表中,为什么我们需要自定义文件管理器。 https://stackoverflow.com/a/19985323/2138633

标签: javaspring-bootspring-securityspring-boot-actuator

解决方案


更新:请参阅有问题的@dur 的评论,它可能会在不进行重大更改的情况下解决问题。

To make it clear, your first security configuration is correct. Your problem 
is that your filter is used as a servlet filter not only as a security chain 
filter. Spring Boot does this autmatically, if you expose your filter.

https://stackoverflow.com/a/39314867/14072498


OP 提到涉及执行器端点。让我们看一下文档: https ://spring.io/guides/topicals/spring-security-architecture

医生说:

If you want your application security rules to apply to the actuator 
endpoints, you can add a filter chain that is ordered earlier than the 
actuator one and that has a request matcher that includes all actuator 
endpoints.

Doc 建议将配置划分为WebSecurityConfigurerAdapter.

在下面的示例配置中,您应该将您称为自定义过滤器的内容应用于MainAppConfigurerAdapter.

“多个 Spring Boot 安全配置”示例: https ://medium.com/@igor.bonny/multiple-spring-boot-security-configuration-c876f1b6061e

为了跳过其他端点的身份验证,添加

.and()
.authorizeRequests().anyRequest().permitAll();

到如下所示的应用程序链的末尾。

要验证安全设置,请为所有端​​点添加集成测试。

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration {

  @Configuration
  @Order(ManagementServerProperties.BASIC_AUTH_ORDER - 1)
  public class ActuatorConfigurerAdapter extends WebSecurityConfigurerAdapter {
    @Override
      protected void configure(HttpSecurity http) {
          http.antMatcher("/actuator/**")
          ...
      }
  }

  @Configuration
  @Order(SecurityProperties.DEFAULT_FILTER_ORDER)
  public class MainAppConfigurerAdapter extends WebSecurityConfigurerAdapter {
      @Override
      protected void configure(HttpSecurity http) {
          http.antMatcher("/api/**")
          ...
      }
  }
}

推荐阅读