SpringBoot在Railway上的应用:GET请求有效但POST请求失败

问题描述 投票:0回答:1

我有一个 SpringBoot 应用程序在带有 Maven 的 Java 17 上运行,使用 SpringBoot 3.2.4。我已将其与 MySQL 数据库一起部署在 Railway 上。部署成功,但我遇到一个问题,即 POST 请求无法正常工作,而 GET 请求正常工作。在我当地,一切都很完美,但在铁路邮政请求不起作用。下面是我的 SecurityConfig 和 SecurityFilterChain 的代码:

@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();
    }
}

这是我在Railway的生产环境: 建筑

当我尝试 POST 请求并从 Postman 收到 401 代码时记录: 可观察性

我尝试启用和禁用 CORS 和 CSRF,但它对我不起作用。我想了解为什么会遇到此错误,以及需要添加、启用或禁用哪些内容才能使我的 POST 请求正常工作。

java spring spring-boot spring-security railway
1个回答
0
投票

要解决 POST 请求在铁路部署中不起作用的问题,您可以在代码中尝试以下解决方案:

显式允许 OPTIONS 请求:有时,CORS(跨源资源共享)问题可能会导致 POST 请求出现问题。确保您的应用程序允许 OPTIONS 请求,这些请求通常是浏览器发送的预检请求,用于检查服务器是否允许实际请求。将 .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll() 添加到您的authorizeHttpRequests方法中。

更新 CSRF 配置:尽管您已经在 SecurityConfig 中禁用了 CSRF 保护,但值得仔细检查它是否在应用程序的所有部分中都已禁用。通过将 .csrf().disable() 添加到您的 httpSecurity 配置中,确保全局禁用 CSRF 保护。

检查重定向:有时,重定向可能会导致 POST 请求出现问题,尤其是当它们更改请求方法时。确保您的应用程序不会将 POST 请求重定向到需要身份验证的另一个端点。您可以将 Spring Security 配置为忽略某些 URL 进行重定向,方法是对这些 URL 使用 .permitAll()。

检查身份验证和授权:仔细检查您的身份验证和授权逻辑,以确保用户经过正确的身份验证和授权来访问 POST 端点。验证 JWT 令牌是否已正确生成和解析,以及角色/权限是否已正确分配给用户。

日志记录和调试:向应用程序添加更多日志记录语句以跟踪请求流并识别任何错误或意外行为。在 IDE 或 Logback 或 Log4j 等日志框架中使用调试模式来获取有关应用程序内部发生情况的详细信息。

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final JwtUtils jwtUtils;

    public SecurityConfig(final JwtUtils jwtUtils) {
        this.jwtUtils = jwtUtils;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .cors().disable()
            .httpBasic(Customizer.withDefaults())
            .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .authorizeRequests(authorize -> authorize
                .antMatchers(HttpMethod.POST, "/api/v1/auth/sign-up").permitAll()
                .antMatchers(HttpMethod.POST, "/api/v1/auth/log-in").permitAll()
                .antMatchers(HttpMethod.POST, "/api/v1/auth/new-password").permitAll()
                .antMatchers(HttpMethod.POST, "/api/v1/auth/test").permitAll()
                .antMatchers(HttpMethod.POST, "/api/v1/auth/test-body").permitAll()
                .antMatchers(HttpMethod.GET, "/api/v1/auth/test").permitAll()
                .antMatchers(HttpMethod.POST, "/api/v1/auth/unlock").hasRole("GERENTE")
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() // Allow OPTIONS requests
                .anyRequest().authenticated()
            )
            .addFilterBefore(new JwtTokenValidator(jwtUtils), BasicAuthenticationFilter.class);
    }

    @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();
    }
}

这些更改应有助于确保您的 POST 请求在 Railway 部署中正常工作。确保在进行这些修改后进行彻底测试。如果问题仍然存在,请继续调试并调查其他潜在原因。

© www.soinside.com 2019 - 2024. All rights reserved.