Spring Security permit all requests - allow all end points
- Details
- Written by Nam Ha Minh
- Last Updated on 29 January 2024   |   Print Email
By default, when Spring Security is present in the classpath, it secures the application - authentication is required to access all resources: all requests and end points must be authenticated. In other words, users need to login or clients need to provide credentials. Otherwise they will get HTTP 401 or 403 error.
This is usually what happened after you add the Spring Security dependency into your project.
What if we want to allow access for all requests temporarily, and implement authentication later? The solution is simple: just code a security configuration class as below (Spring Boot 3.x and Spring Security 6.x):
package net.codejava; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.web.SecurityFilterChain; @Configuration public class SecurityConfig { @Bean SecurityFilterChain configure(HttpSecurity http) throws Exception { http.authorizeHttpRequests(auth -> auth.anyRequest().permitAll()); return http.build(); } }
Here, the code in the configure() method permit all requests having access without authentication. In API applications, that means clients are allowed to access all end points without authentication or authorization.
With older versions (Spring Boot 2.x and Spring Security 5.x), the code of the configuration class looks like this:
package net.codejava; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().anyRequest().permitAll(); } }
This would be helpful when the security features are being implemented while existing functionalities can be still tested normally.
Watch the following video to see the coding in action:
Learn more about Spring Security:
- Spring Security Authentication with JPA, Hibernate and MySQL
- Spring Security Role-based Authorization Tutorial
- Spring Security Customize Login and Logout
- Spring Security JWT Authentication Tutorial
- Spring Security JWT Role-based Authorization Tutorial
- Full Spring Security Tutorials
Comments