๐ด The Error You're Seeing
Confirm this matches your console output. If it does, you're in the right place.
2023-10-25 10:15:30.812 WARN 12345 --- [nio-8080-exec-1] o.s.s.web.util.matcher.OrRequestMatcher :
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Wed Oct 25 10:15:30 IST 2023
There was an unexpected error (type=Forbidden, status=403).โก Quick Fix Works 80% of the time
Configure your SecurityFilterChain to permit all requests for testing.
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(auth -> auth.anyRequest().permitAll());
return http.build();
}๐ ๏ธ Solutions (3 Ways to Fix)
Configure permitAll() in SecurityFilterChain
๐ Use this during development when you want to test APIs without security.
By default, Spring Security blocks all endpoints. You must explicitly tell it to permit requests.
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth.anyRequest().permitAll());
return http.build();
}
}Define specific URL rules
๐ Use this when you want some endpoints public and others secured.
Use requestMatchers to define which URLs are public and which require authentication.
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/public/**").permitAll()
.anyRequest().authenticated()
);
return http.build();
}Remove spring-boot-starter-security
๐ Use this if you added security by accident and don't need it.
If you don't need authentication, simply remove the dependency from your pom.xml.
<!-- Remove this from pom.xml -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>๐ Version Notes
Uses WebSecurityConfigurerAdapter (deprecated).
Uses SecurityFilterChain bean. Lambda DSL is required. CSRF is enabled by default, blocking POST/PUT.
๐ง Why this Happens
Tap to expand the deep technical explanation
When you add spring-boot-starter-security to your project, Spring Boot auto-configures a default security filter that blocks ALL HTTP requests. It also enables CSRF protection by default, which blocks POST, PUT, and DELETE requests. You must define a SecurityFilterChain bean to override this.
The HITEC City Parking Spot Analogy:
It's like hiring a bouncer for your restaurant, but forgetting to tell him who is allowed in. He defaults to kicking everyone out.
๐ก๏ธ How to Prevent This Next Time
Always create a SecurityConfig class immediately after adding the Spring Security dependency.