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:



 


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Add comment