spring security 403 error

SpringSpring MvcSpring Security

Spring Problem Overview


I'm trying to secure my website using Spring security following the guides on the web. So on my server side the WebSecurityConfigurerAdapter and controller looks like this

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
implements ApplicationContextAware {

@Override
protected void registerAuthentication(AuthenticationManagerBuilde r authManagerBuilder) throws Exception {
authManagerBuilder.inMemoryAuthentication()
.withUser("user").password("password").roles("ADMI N");
}
}

@Controller
//@RequestMapping("/course")
public class CourseController implements ApplicationContextAware{

@RequestMapping(value="/course", method = RequestMethod.GET, produces="application/json")
public @ResponseBody List<Course> get(// The critirion used to find.
@RequestParam(value="what", required=true) String what,
@RequestParam(value="value", required=true) String value) {
//.....
}

@RequestMapping(value="/course", method = RequestMethod.POST, produces="application/json")
public List<Course> upload(@RequestBody Course[] cs) {
}
}

What confused me very much is the server does not respond to the POST/DELETE method, while the GET method works fine. BTW, I'm using RestTemplate on the client side. Exceptions are:

Exception in thread "main" org.springframework.web.client.HttpClientErrorException: 403 Forbidden
	at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91)
	at org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:574)
	at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:530)
	at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:487)
	at org.springframework.web.client.RestTemplate.delete(RestTemplate.java:385)
	at hello.Application.createRestTemplate(Application.java:149)
	at hello.Application.main(Application.java:99)

I've searched the internet for days. Still don't have a clue. Please help. Thanks so much

Spring Solutions


Solution 1 - Spring

The issue is likely due to CSRF protection. If users will not be using your application in a web browser, then it is safe to disable CSRF protection. Otherwise you should ensure to include the CSRF token in the request.

To disable CSRF protection you can use the following:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig
    extends WebSecurityConfigurerAdapter implements ApplicationContextAware {

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

    @Override
    protected void registerAuthentication(AuthenticationManagerBuilder authManagerBuilder) throws Exception {
        authManagerBuilder
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("ADMIN");
    }
}

Solution 2 - Spring

The issue may be related to CSRF or CORS Security Protection.

  • FOR CSRF: You can disable it if the application users did not use it from browsers.
  • For CORS: You can specify the origin and allow HTTP Methods.

The below code disable CSRF and allow all origins and HTTP methods. so be aware when using it.

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter  implements WebMvcConfigurer {

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

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedMethods("*");
    }

}

Solution 3 - Spring

The issue is likely due to CSRF protection, agree with the top comment. Nevertheless, by using this configuration, the method cancells the spring security.

So you can use the following code:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();

        auth
                .inMemoryAuthentication()
                    .withUser("admin")
                        .password(encoder.encode("admin"))
                        .roles("ADMIN", "USER")
                .and()
                    .withUser("user")
                        .password(encoder.encode("password"))
                        .roles("USER");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .httpBasic();

        http.csrf().disable();
    }
}

Solution 4 - Spring

I've been looking for days too! Simply disabling CSRF on your configure method with http.csrf().disable(); is all that needed to be done for my put requests to stop receiving 403.

Solution 5 - Spring

Check your token which you are sending through 'Header' and also query in your database for the same token whether that token exist or not.

Note : The above is applicable only in case you are using Spring Boot token authentication mechanism.

Solution 6 - Spring

http.httpBasic().disable();
http.authorizeRequests().antMatchers("/signup").permitAll().antMatchers("/*")
     .fullyAuthenticated().and().formLogin()
     .and().csrf().disable();
http.csrf().disable();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkenView Question on Stackoverflow
Solution 1 - SpringRob WinchView Answer on Stackoverflow
Solution 2 - SpringOmar GhaziView Answer on Stackoverflow
Solution 3 - SpringbigdbaView Answer on Stackoverflow
Solution 4 - Spring8ryan8View Answer on Stackoverflow
Solution 5 - SpringManas Ranjan MahapatraView Answer on Stackoverflow
Solution 6 - SpringSagar TalrejaView Answer on Stackoverflow