How to Solve 403 Error in Spring Boot Post Request

前端 未结 3 788
醉酒成梦
醉酒成梦 2020-12-24 10:44

I am newbie in spring boot rest services. I have developed some rest api in spring boot using maven project.

I have successfully developed Get and <

相关标签:
3条回答
  • 2020-12-24 11:17

    To build on the accepted answer

    Many HTTP client libraries (eg Axios) implicitly set a Content-Type: JSON header for POST requests. In my case, I forgot to allow that header causing only POSTS to fail.

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        ...
        configuration.addAllowedHeader("Content-Type"); // <- ALLOW THIS HEADER 
        ...
    }
    
    0 讨论(0)
  • 2020-12-24 11:25

    you have to disable csrf Protection because it is enabled by default in spring security: here you can see code that allow cors origin.

    import org.springframework.context.annotation.Bean;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    import org.springframework.web.cors.CorsConfiguration;
    import org.springframework.web.cors.CorsConfigurationSource;
    import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
    
    @EnableWebSecurity
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
    
        @Override
        protected void configure(HttpSecurity http) throws Exception{
            http.cors().and().csrf().disable();
        }
    
        @Bean
        CorsConfigurationSource corsConfigurationSource() {
            CorsConfiguration configuration = new CorsConfiguration();
            configuration.setAllowedOrigins(Arrays.asList("*"));
            configuration.setAllowedMethods(Arrays.asList("*"));
            configuration.setAllowedHeaders(Arrays.asList("*"));
            configuration.setAllowCredentials(true);
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            source.registerCorsConfiguration("/**", configuration);
            return source;
        }
    
    }
    
    0 讨论(0)
  • 2020-12-24 11:26

    Possible causes:

    1. Requests done from postman are different to the one done from mobile (uri, method, headers)
    2. Invalid token
    3. CORS (read something about it, google is full of articles) add @CrossOrigin annotation to your controller.
    4. mobile app is doing an OPTION request before performing the POST, and you block OPTION requests. If also from postman the OPTION requests are blocked, add the property spring.mvc.dispatch-options-request=true. Moreover, in case you are using spring security, you have to explicitly allow OPTION requests also for it.
    0 讨论(0)
提交回复
热议问题