[Fixed] Spring Security permitAll not working
- Details
- Written by Nam Ha Minh
- Last Updated on 05 July 2024   |   Print Email
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:
- Spring Security Registration and Login Tutorial
- Spring Security Role-based Authorization Tutorial
- Spring Security Remember Me Examples
- Spring Security Forgot Password Tutorial
- Spring Security Social Login with Google and Facebook
- Full Spring Security Tutorials List
Comments