【问题标题】:Exclude requests to URL from being run through Spring Security filters通过 Spring Security 过滤器排除对 URL 的请求
【发布时间】:2020-10-15 18:16:28
【问题描述】:

我有一个 Spring Boot 应用程序和一个自定义身份验证过滤器。该应用程序有一个 URL“/”,我希望避免运行任何 Spring Security 过滤器(包括身份验证和授权),包括我的自定义过滤器。

我不想将WebSecurity 配置为忽略此 URL,因为我想应用一些其他 Spring Security 功能,我的理解是使用:

webSecurityBuilder.ignoring().antMatchers("/");

将阻止 所有 Spring Security 功能在此 URL 上运行。

有没有办法为此使用 HttpSecurity?

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomAuthenticationFilter customAuthFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        
http.antMatcher("/").
                anonymous().and().authorizeRequests()
                .antMatchers("/", "/index.html").permitAll()
                .anyRequest().authenticated();

        http.addFilterBefore(customAuthFilter, UsernamePasswordAuthenticationFilter.class);

    }

这是我目前所拥有的,但由于某种原因,当我导航到“/”时,我仍然点击了我的自定义过滤器。

【问题讨论】:

    标签: java spring spring-security


    【解决方案1】:

    以下是解决方案。抽象是您应该定义两个具有不同顺序的 WebSecurityConfigurerAdapter。请试一试。 solution

    下面的代码是从那里复制过来的。

    @Configuration
    @Order(1)
    public class OnlyHeadersConfig extends WebSecurityConfigurerAdapter {
        protected void configure(HttpSecurity http) {
            http
                .antMatchers("/special/endpoints/**")
                    .authorizeRequests((authz) -> authz.anyRequest().permitAll())
                    .anonymous();
        }
    }
    
    @Configuration
    @Order(2)
    public class MainSecurityConfig extends WebSecurityConfigurerAdapter {
        protected void configure(HttpSecurity http) {
            http
                .authorizeRequests(authz -> authz.anyRequest().authenticated())
                .addFilterAt(new MyCustomFilter(), UsernamePasswordAuthenticationFilter.class);
        }
    }
    

    【讨论】:

    • 我做了测试,证明没问题
    猜你喜欢
    • 2013-04-13
    • 1970-01-01
    • 2016-06-24
    • 2014-01-31
    • 2018-03-14
    • 2020-07-10
    • 1970-01-01
    • 2021-04-27
    • 1970-01-01
    相关资源
    最近更新 更多