401 在请求中指定了 `permitAll()`

401 on request where `permitAll()` specified

我有这个 WebSecurityConfigurerAdapter 配置:

@EnableWebSecurity
public class HttpSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.cors()
                .and()
                .authorizeRequests()

                .mvcMatchers("/auth/**").permitAll()

                .anyRequest().authenticated()

                .and()
                .oauth2ResourceServer().jwt()
        ;
    }
}

当我向 auth 发出请求时,我收到 401,直到我通过一些授权 - 这不适合此 endopint。

我认为这与 .anyRequest().authenticated() 有关。我之前读过这不应该影响 permitAll()s - 我配置错误了吗?

如果您使用的是 jwt 过滤器,即使您添加了 permitAll() 它也不会工作。如果您删除过滤器,它将正常工作。

您的请求可能被拒绝,因为您没有提供 CSRF token。默认情况下,Spring 安全性会为每个 POST 请求启用它,您需要明确禁用它。

@EnableWebSecurity
public class HttpSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.cors()
                .and()
                .csrf().disable()
                .authorizeRequests()
                .mvcMatchers("/auth/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .oauth2ResourceServer().jwt();
    }
}

您可以将以下 属性 添加到您的 application.yml 文件中,这样您就可以了解如果 CSRF 不是这种情况,您的请求被拒绝的原因:

logging:
  level:
    org.springframework.security: TRACE