部署在Railway的SpringBoot应用GET正常POST请求失败问题排查与解决
生产环境POST请求401异常排查与解决
问题背景
基于Java 17、Maven构建的SpringBoot 3.2.4应用,集成Spring Security 6后部署至Railway平台并搭配MySQL数据库。本地开发环境一切正常,但生产环境中GET请求可正常响应,POST请求却返回401未授权状态码。
现有Security配置
@Configuration @EnableWebSecurity @EnableMethodSecurity public class SecurityConfig { private final JwtUtils jwtUtils; public SecurityConfig(final JwtUtils jwtUtils) { this.jwtUtils = jwtUtils; } @Bean public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception { return httpSecurity .csrf(AbstractHttpConfigurer::disable) .cors(AbstractHttpConfigurer::disable) .httpBasic(Customizer.withDefaults()) .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .authorizeHttpRequests(http -> { // public endpoints http.requestMatchers(HttpMethod.POST, "\/api\/v1\/auth\/sign-up").permitAll(); http.requestMatchers(HttpMethod.POST, "\/api\/v1\/auth\/log-in").permitAll(); http.requestMatchers(HttpMethod.POST, "\/api\/v1\/auth\/new-password").permitAll(); http.requestMatchers(HttpMethod.POST, "\/api\/v1\/auth\/test").permitAll(); http.requestMatchers(HttpMethod.POST, "\/api\/v1\/auth\/test-body").permitAll(); http.requestMatchers(HttpMethod.GET, "\/api\/v1\/auth\/test").permitAll(); // private endpoints http.requestMatchers(HttpMethod.POST, "\/api\/v1\/auth\/unlock").hasRole("GERENTE"); }) .addFilterBefore(new JwtTokenValidator(jwtUtils), BasicAuthenticationFilter.class) .build(); } @Bean public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception { return authenticationConfiguration.getAuthenticationManager(); } @Bean public AuthenticationProvider authenticationProvider(UserDetailsServiceImpl userDetailsService) { DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); provider.setPasswordEncoder(passwordEncoder()); provider.setUserDetailsService(userDetailsService); return provider; } @Bean public PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } }
已尝试操作
- 开启/关闭CORS配置
- 开启/关闭CSRF配置
以上操作均未解决问题。
解决方法及原因分析
解决步骤
- 在SecurityFilterChain的授权规则中添加OPTIONS请求全局放行:
http.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll();
- 将请求协议从
http://改为https://
原因分析
- 预检OPTIONS请求未放行:生产环境中,浏览器或平台网关会对跨域POST请求发送预检OPTIONS请求,若Spring Security未放行该请求,会直接返回401,导致后续实际POST请求无法执行。
- 协议不匹配:Railway生产环境默认使用HTTPS协议,若请求仍使用HTTP,会导致请求被重定向,过程中可能丢失JWT认证令牌或令牌验证失败,最终返回401未授权。
内容的提问来源于stack exchange,提问作者Andrés Camilo Jiménez Mantilla
相关产品推荐
相关产品推荐

