When developing REST API with Spring framework and Spring Security, you may use permitAll() to enable public access to all endpoints for testing easily without authentication, like this:

@Configuration
public class SecurityConfig {

    @Bean	
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

    	http.authorizeHttpRequests(auth -> auth.anyRequest().permitAll());
    	
    	return http.build();
    }
    
}

However, when testing an endpoint with HTTP POST, e.g. /api/oauth/token, you still get 403 Forbidden error like this:

{
    "status": 403,
    "error": "Forbidden",
    "message": "Forbidden",
    "path": "/api/oauth/token"
}

It looks weird! You already permit all access but it seems does not working. What is the reason?

Well, it’s simply because when you use Spring Boot with auto configuration for Spring Security, CSRF is enabled by default for Cross Site Request Forgery attack protection. That means any POST request must supply a CSRF token value generated by Spring Security in order to reach the destination handler.

So to fix this issue, just disable CSRF in your security configuration code, for example:

@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

	http.authorizeHttpRequests(
			auth -> auth.anyRequest().permitAll()
		).csrf(csrf -> csrf.disable());
	
	return http.build();
}

Test your API again and it will work. Note that disabling CRSF is safe for REST APIs because CSRF protection is needed only for web form submissions.

You can also watch the following video to see the coding in a real project:

 

Related Spring Security Articles:

 

Learn more about Spring Security:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.

Add comment