403 forbidden when I try to post to my spring api?

后端 未结 4 703
青春惊慌失措
青春惊慌失措 2021-02-05 22:59

Using postman, I can get a list of users with a get request to: http://localhost:8080/users.

But when I send a post request to the same address, I get a 40

相关标签:
4条回答
  • 2021-02-05 23:32

    When you use spring boot with spring security and if you are accessing your API's(POST, PUT, DELETE) from Postman or something, they wont be accessible and error is related to authorization like forbidden 403.

    So in that case, you have to disabled to csrf functionality to run and test the API from Postman.

    The answer provided by @benjamin c is right. You have to add the class with the this configuration will work.

    Make sure you are removing this when you add your code in production. CSRF protection is must and you have to keep it in security functionality.

    I am just extending his answer for more details by providing complete class details. My requirement was to just test the API from Postman, so I added this class, and able to test the API from Postman.

    But after that I have added Spring Junit classes to test my functionalities and removed this class.

    @Configuration
    @EnableWebSecurity
    public class AppWebSecurityConfigurer extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {    
            http
                .csrf().disable()
                .authorizeRequests()
                    .anyRequest().permitAll();
            }
    }
    

    Hope this helps to someone.

    0 讨论(0)
  • 2021-02-05 23:35

    403 means you don't have authorization. Even though you commented out your method, your code will still be preconfigured with default security access.

    You can add:

    http.authorizeRequests()
       .antMatchers("/users/**").permitAll();
    

    UPDATE : The configuration with csrf disabled:

    http.csrf()
         .ignoringAntMatchers("/users/**")
         .and()
         .authorizeRequests()
            .antMatchers("/users/**").permitAll();
    
    0 讨论(0)
  • 2021-02-05 23:36

    @EnableWebSecurity enables spring security and it by default enables csrf support, you must disable it in order to prevent 403 errors.

    @Override
    protected void configure(HttpSecurity http) throws Exception {
         http.csrf().disable();
    }
    

    Or send csrf token with each request.

    Note: disabling csrf makes application less secure, best thing to do is send csrf token.

    0 讨论(0)
  • 2021-02-05 23:41

    Please configure your http like this ;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            //configureothers if u wants.
            .csrf().disable();
    }
    

    Please read for more CSRF

    0 讨论(0)
提交回复
热议问题