【问题标题】:Spring security antMatchers permitAll doesn't workSpring security antMatchers permitAll 不起作用
【发布时间】:2018-01-31 15:37:19
【问题描述】:

我知道有这个问题的主题,但我所做的配置是正确的,我将它与一个正常工作的项目进行了比较。 我想为 JWT 安全性“取消保护” /login 端点,但 AuthenticationFilter 在到达 /login 端点之前仍然运行。 我很困惑为什么它不起作用。

我的代码如下:

@Override
    protected void configure(HttpSecurity http) throws Exception {

        http
                .csrf().disable()

                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()

                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()

                .authorizeRequests()

                .antMatchers("/login").permitAll()
                .anyRequest().authenticated();

        http
                .addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);

        http.headers().cacheControl();

    }

【问题讨论】:

标签: spring spring-security permissions


【解决方案1】:

重复How to add a filter only for one special path WebSecurityConfigurerAdapter

您不能使用单个配置类来做到这一点。看看这个问题:How to apply spring security filter only on secured endpoints?

在这种情况下,我认为更好的解决方案是配置多个HttpSecurity。来自Spring IO documentation

我们可以配置多个 HttpSecurity 实例,就像我们可以拥有的一样 多个块。关键是延长 WebSecurityConfigurationAdapter 多次。例如, 以下是对 URL 进行不同配置的示例 以 /api/ 开头。

文档中有一个完整的示例,其中包含完成此操作的必要步骤:

  1. 正常配置身份验证
  2. 创建一个 WebSecurityConfigurerAdapter 实例,其中包含 @Order 指定应该是哪个 WebSecurityConfigurerAdapter 优先考虑。
  3. http.antMatcher 声明此 HttpSecurity 仅适用于以 /api/ 开头的 URL
  4. 创建另一个 WebSecurityConfigurerAdapter 实例。如果 URL 不以 /api/ 开头,则将使用此配置。这 在 ApiWebSecurityConfigurationAdapter 之后考虑配置 因为它在 1 之后有一个 @Order 值(没有 @Order 默认为最后一个)。

祝你好运!

【讨论】:

猜你喜欢
  • 2019-09-27
  • 1970-01-01
  • 1970-01-01
  • 2018-03-27
  • 2016-02-16
  • 1970-01-01
  • 2017-08-20
  • 1970-01-01
  • 2020-10-02
相关资源
最近更新 更多