【问题标题】:Filter ordering with spring security and spring boot使用 spring security 和 spring boot 过滤排序
【发布时间】:2018-01-15 10:35:54
【问题描述】:

我正在尝试使用 Spring Security 来保护使用 JWT 令牌的休息/无状态 api。从我看到的研究来看,它涉及关闭 spring 安全会话管理,然后添加一些自定义过滤器来处理用户登录以及检查 jwt 令牌。

我遇到的问题是,一旦我添加了一个过滤器,它就会在每一个而不是我想要它的端点上运行。我需要打开登录端点以及其他一些有助于注册和参考不需要保护的数据的端点。

@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/api/user").permitAll()
                .anyRequest().authenticated().and()
                .addFilterBefore(new StatelessAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
        ;
    }
}

StatelessAuthenticationFilter 所做的只是打印“in here”。我只希望在您转到 localhost:8080/api/order 时看到该消息打印,但是当您转到 localhost:8080/api/user 时我看到它显示出来。

有没有办法获得这种行为?

【问题讨论】:

    标签: java spring spring-mvc spring-security


    【解决方案1】:

    按照您的配置方式,HttpSecurity 将应用于包括用户端点在内的所有 URL。 authorizeRequests() .antMatchers("/api/user").permitAll() 行不会阻止调用身份验证过滤器的“用户”端点。 它只是说任何经过身份验证的用户都可以调用它。 您只需将过滤器应用于“订单”端点。像这样: http .requestMatchers().antMatchers("/api/user") .and() .authorizeRequests()

    【讨论】:

    • 我试过了,它成功了!我还看到您可以覆盖 configure(Websecurity) 方法并使用 ignoring() 方法来忽略端点。我不太确定首选哪种方式。
    【解决方案2】:

    @tsolakp 的回答对我有用。我最终覆盖了

    configure(Websecurity) 方法虽然

     @Override
      public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/api/user");
      }
    
    @Override
      protected void configure(HttpSecurity http) throws Exception {
        http
          .csrf().disable()
          .authorizeRequests()
            .anyRequest().authenticated().and()
            .addFilterBefore(new StatelessAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
        ;
      }
    

    【讨论】:

      猜你喜欢
      • 2021-12-06
      • 2019-07-16
      • 2015-06-09
      • 1970-01-01
      • 2015-10-19
      • 2022-07-29
      • 2019-12-30
      • 2014-07-25
      • 2019-10-01
      相关资源
      最近更新 更多