Spring Security 6配置permitAll仍返回401问题排查
解决方案:Spring Security 实现GET免认证、POST需认证
问题根源在于引入oauth2-resource-server依赖后,Spring Security自动配置会默认启用JWT认证过滤器,即便你没显式配置,这个过滤器也会拦截所有请求校验token,导致GET请求也返回401。以下是正确的配置方式:
@Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth .requestMatchers(HttpMethod.GET).permitAll() .anyRequest().authenticated() ) .oauth2ResourceServer(oauth2 -> oauth2 .jwt(Customizer.withDefaults()) ) .csrf().disable(); return http.build(); }
关键说明:
- 明确通过
requestMatchers(HttpMethod.GET).permitAll()让所有GET请求直接放行,无需经过认证校验 - 配置
oauth2ResourceServer并启用JWT,确保授权规则优先级高于过滤器生效逻辑 - 禁用CSRF(若你的POST请求不需要CSRF令牌可保留此配置,根据实际场景调整)
如果仅需特定路径的GET请求放行,可指定具体路径,示例:
.requestMatchers(HttpMethod.GET, "/", "/api/public/**").permitAll()
按此配置后,未认证用户访问GET请求会返回200,POST请求会返回401,完全匹配你的需求。
内容的提问来源于stack exchange,提问作者Jose Gleeson
相关产品推荐
相关产品推荐

