Spring Security 6.2配置JWT认证时非GET请求返回401问题排查
Spring Security 6.2 OAuth2资源服务器JWT认证非GET请求401问题
我在Spring Security 6.2中引入OAuth2资源服务器依赖后遇到以下问题:
- 使用基本认证时,即便配置允许所有请求类型,仅能执行GET方法,禁用CSRF保护后解决了该问题;
- 切换为JWT认证后,已禁用CSRF保护,但问题仍存在:仅GET方法可正常访问,POST、PUT等其他方法均返回401 Unauthorized状态。
SecurityConfig.java
@EnableWebSecurity @Configuration public class SecurityConfig { @Autowired UserDetailsServiceImpl userDetailsService; @Autowired PasswordEncoder passwordEncoder; @Value("${jwt.secretKey}") private String secretKey; @Bean SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception { httpSecurity.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .csrf(AbstractHttpConfigurer::disable) .authorizeHttpRequests(authorize -> authorize.anyRequest().permitAll()); httpSecurity.oauth2ResourceServer((oauth2) -> oauth2.jwt(Customizer.withDefaults())); return httpSecurity.build(); } @Bean public JwtEncoder jwtEncoder() { return new NimbusJwtEncoder(new ImmutableSecret<>(secretKey.getBytes())); } @Bean public JwtDecoder jwtDecoder() { SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), "RSA"); return NimbusJwtDecoder.withSecretKey(secretKeySpec).macAlgorithm(MacAlgorithm.HS512).build(); } @Bean AuthenticationManager authenticationManager() { DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider(); daoAuthenticationProvider.setPasswordEncoder(passwordEncoder); daoAuthenticationProvider.setUserDetailsService(userDetailsService); return new ProviderManager(daoAuthenticationProvider); } }
请求头与响应头截图显示相关认证信息
调试日志:
2023-08-23T22:15:43.044+01:00 DEBUG 7880 --- [nio-8081-exec-1] o.s.security.web.FilterChainProxy : Securing POST /auth/login 2023-08-23T22:15:43.051+01:00 DEBUG 7880 --- [nio-8081-exec-1] o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder to anonymous SecurityContext 2023-08-23T22:15:43.052+01:00 DEBUG 7880 --- [nio-8081-exec-1] o.s.security.web.FilterChainProxy : Secured POST /auth/login
内容的提问来源于stack exchange,提问作者hazem_bensaid
相关产品推荐
相关产品推荐

