clientRegistrationRepository cannot be null - oauth-2.0

Keycloak OAuth 2.0 clientRegistrationRepository cannot be null.
Hello, discovered a problem, when trying to make use of OAuth 2.0 in my application. It fails after the startup. Message:
Exception encountered during context initialization - cancelling
refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name
'org.springframework.security.config.annotation.web.reactive.WebFluxSecurityConfiguration':
Unsatisfied dependency expressed through method
'setSecurityWebFilterChains' parameter 0; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'springSecurityFilterChain' defined in class
path resource
[com/microservices/apigateway/security/SecurityConfig.class]: Bean
instantiation via factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate
[org.springframework.security.web.server.SecurityWebFilterChain]:
Factory method 'springSecurityFilterChain' threw exception; nested
exception is java.lang.IllegalArgumentException:
clientRegistrationRepository cannot be null
Cannot find any info in the net about the possible nature of this problem.
SecurityConfig
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;
#Configuration
#EnableWebFluxSecurity
public class SecurityConfig {
#Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
.authorizeExchange()
.pathMatchers("/actuator/**")
.permitAll()
.and()
.authorizeExchange()
.anyExchange()
.authenticated()
.and()
.oauth2Login() // to redirect to oauth2 login page.
;
return http.build();
}
}
application.properties
spring.application.name=api-gateway
server.port=8765
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka
#spring.cloud.gateway.discovery.locator.enabled=true
#spring.cloud.gateway.discovery.locator.lowerCaseServiceId=true
spring.sleuth.sampler.probability=1.0
spring.security.oauth2.client.provider.myprovider.issuer-uri=http://localhost:8083/realms/MyMicroservicesRealm
spring.security.oauth2.client.provider.myprovider.authorization-uri=http://localhost:8083/realms/MyMicroservicesRealm/protocol/openid-connect/auth
spring.security.oauth2.client.provider.myprovider.token-uri=http://localhost:8083/realms/MyMicroservicesRealm/protocol/openid-connect/token
spring.security.oauth2.client.provider.myprovider.jwk-set-uri=http://localhost:8083/realms/MyMicroservicesRealm/protocol/openid-connect/certs
spring.security.oauth2.client.provider.myprovider.user-info-uri=http://localhost:8083/realms/MyMicroservicesRealm/protocol/openid-connect/userinfo
spring.security.oauth2.client.provider.mywebclient.user-name-attribute = preferred_username
spring.security.oauth2.client.registration.myclient.provider=myprovider
spring.security.oauth2.client.registration.myclient.scope=openid, profile, roles
spring.security.oauth2.client.registration.myclient.client-id=gateway-client
spring.security.oauth2.client.registration.myclient.client-secret=ajKhFIsMi3qJNlXkVTS8AFhYwhv3TUSh
spring.security.oauth2.client.registration.myclient.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.myclient.redirect-uri="{baseUrl}/login/oauth2/code/keycloak"
logging.level.org.springframework.security.web=DEBUG

Resolved by removing spring-boot-starter-web dependency

Related

Spring Security LDAP Changes After 5.7

I am trying to understand the steps to support LDAP with Spring security...replacing our current basic authentication. Recently I made the changes to support the deprecation of the WebSecurityConfigurerAdapter and all is working fine. So now I want to swap out the basic authentication AuthenticationManager or AuthenticationProvider with their LDAP equivalents. There are several websites with partial information and I cant quite put the pieces together.
So I am starting with the spring guide on authenticating ldap (https://github.com/spring-guides/gs-authenticating-ldap) I took the "complete" example, modified for our version of Spring Boot 2.7.5 and the app starts and validates fine. I tried updating the example according to several websites from :
#Autowired
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.ldapAuthentication()
.userDnPatterns("uid={0},ou=people")
.groupSearchBase("ou=groups")
.contextSource()
.url("ldap://localhost:8389/dc=springframework,dc=org")
.and()
.passwordCompare()
.passwordEncoder(new BCryptPasswordEncoder())
.passwordAttribute("userPassword");
To :
#Bean
public EmbeddedLdapServerContextSourceFactoryBean contextSourceFactoryBean() {
EmbeddedLdapServerContextSourceFactoryBean contextSourceFactoryBean =
EmbeddedLdapServerContextSourceFactoryBean.fromEmbeddedLdapServer();
contextSourceFactoryBean.setPort(0);
return contextSourceFactoryBean;
}
#Bean
public AuthenticationManager authenticationManager(BaseLdapPathContextSource contextSource) {
LdapPasswordComparisonAuthenticationManagerFactory factory = new LdapPasswordComparisonAuthenticationManagerFactory(
contextSource, new BCryptPasswordEncoder());
factory.setUserDnPatterns("uid={0},ou=people");
factory.setPasswordAttribute("pwd");
return factory.createAuthenticationManager();
}
Thinking this closer to the recommendations and closer to what I would be using in our real project. Now when I try to build ... the test phase keeps failing with the following stack trace
ERROR[m] loginWithValidUserThenAuthenticated Time elapsed: 0 s <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'authenticationManager' defined in class path resource [com/example/authenticatingldap/WebSecurityConfig.class]: Unsatisfied dependency expressed through method 'authenticationManager' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'contextSourceFactoryBean': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalStateException: Unable to load LDIF classpath*:*.ldif
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'contextSourceFactoryBean': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalStateException: Unable to load LDIF classpath*:*.ldif
Caused by: java.lang.IllegalStateException: Unable to load LDIF classpath*:*.ldif
Caused by: com.unboundid.ldap.sdk.LDAPException: An entry with DN 'dc=springframework,dc=org' already exists in the server.
I am using the same ldif file that worked with the other configuration. The code follows the other examples and recommendation but the embedded LDAP server wont load the file. Has anyone seen and solved this problem? Once this is working, do we simply remove the Embedded LDAP bean and somehow point the configuration to the real LDAP server?

How to implement config in AbstractHttpConfigurer's *before* local HttpSecurity code

I'm updating an internal library and applications to Spring Boot 3 (which updated to Spring Security 6).
We have common security configuration which I've updated to implement AbstractHttpConfigurer e.g.
public class WebberWebSecurityConfigurerAdapter
extends AbstractHttpConfigurer<WebberWebSecurityConfigurerAdapter, HttpSecurity> {
public void configure(final HttpSecurity http) throws Exception {
http
.authorizeHttpRequests()
.requestMatchers(HEALTH_CHECK_PATH).permitAll()
}
}
The web application then has:
#Configuration
public class SecurityConfig {
#Bean
public SecurityFilterChain config(HttpSecurity http) throws Exception {
http.apply(new WebberWebSecurityConfigurerAdapter());
http
.authorizeHttpRequests()
.requestMatchers("/", "/request-info", "/test").permitAll()
.anyRequest().authenticated();
return http.build();
}
}
This throws the exception:
Caused by: java.lang.IllegalStateException: Can't configure requestMatchers after anyRequest
Presumably because Spring is trying to configure the .requestMatchers(HEALTH_CHECK_PATH).permitAll() line after the .anyRequest().authenticated(); line, despite it being specified first in the config.
How do I get Spring to configure all the upstream library config first, before applying the custom config from the web application itself?

Declaring AuthenticationManager Bean throws exception "Cannot apply DaoAuthenticationConfigurer to already built object"

My UserServiceImpl class extends the UserDetailsService interface, and i have overriden the loadUserByUsername() method, I declared an AuthenticationManager bean, and using the builder, passed it my userDetailsService implementation and preferred password encoder.
Here's my security config class :
#Configuration
#EnableWebSecurity
public class UserManagmentConfig {
#Autowired
private UserDetailsService userDetailsService;
#Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Bean
public AuthenticationManager authenticationManager(AuthenticationManagerBuilder builder) throws Exception {
return builder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()).and().build();
}
}
And my WebAuthorization config :
public class WebAuthorizationConfig {
#Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.formLogin();
http.authorizeRequests().anyRequest().authenticated();
return http.build();
}
}
This is the exception i get when launching the app :
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'authenticationManager' defined in class path resource [app/ticketme/securityconfig/UserManagmentConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.authentication.AuthenticationManager]: Factory method 'authenticationManager' threw exception; nested exception is java.lang.IllegalStateException: Cannot apply org.springframework.security.config.annotation.authentication.configurers.userdetails.DaoAuthenticationConfigurer#14d513ca to already built object
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:658) ~[spring-beans-5.3.21.jar:5.3.21]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:638) ~[spring-beans-5.3.21.jar:5.3.21]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1352) ~[spring-beans-5.3.21.jar:5.3.21]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1195) ~[spring-beans-5.3.21.jar:5.3.21]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582) ~[spring-beans-5.3.21.jar:5.3.21]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.21.jar:5.3.21]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.21.jar:5.3.21]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.21.jar:5.3.21]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.21.jar:5.3.21]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.21.jar:5.3.21]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:955) ~[spring-beans-5.3.21.jar:5.3.21]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) ~[spring-context-5.3.21.jar:5.3.21]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.21.jar:5.3.21]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:147) ~[spring-boot-2.7.1.jar:2.7.1]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:734) ~[spring-boot-2.7.1.jar:2.7.1]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408) ~[spring-boot-2.7.1.jar:2.7.1]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) ~[spring-boot-2.7.1.jar:2.7.1]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306) ~[spring-boot-2.7.1.jar:2.7.1]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1295) ~[spring-boot-2.7.1.jar:2.7.1]
at app.ticketme.Main.main(Main.java:10) ~[classes/:na]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.authentication.AuthenticationManager]: Factory method 'authenticationManager' threw exception; nested exception is java.lang.IllegalStateException: Cannot apply org.springframework.security.config.annotation.authentication.configurers.userdetails.DaoAuthenticationConfigurer#14d513ca to already built object
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.3.21.jar:5.3.21]
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:653) ~[spring-beans-5.3.21.jar:5.3.21]
... 19 common frames omitted
Caused by: java.lang.IllegalStateException: Cannot apply org.springframework.security.config.annotation.authentication.configurers.userdetails.DaoAuthenticationConfigurer#14d513ca to already built object
at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.add(AbstractConfiguredSecurityBuilder.java:182) ~[spring-security-config-5.7.2.jar:5.7.2]
at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.apply(AbstractConfiguredSecurityBuilder.java:125) ~[spring-security-config-5.7.2.jar:5.7.2]
at org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder.apply(AuthenticationManagerBuilder.java:280) ~[spring-security-config-5.7.2.jar:5.7.2]
at org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder.userDetailsService(AuthenticationManagerBuilder.java:182) ~[spring-security-config-5.7.2.jar:5.7.2]
at org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration$DefaultPasswordEncoderAuthenticationManagerBuilder.userDetailsService(AuthenticationConfiguration.java:291) ~[spring-security-config-5.7.2.jar:5.7.2]
at app.ticketme.securityconfig.UserManagmentConfig.authenticationManager(UserManagmentConfig.java:31) ~[classes/:na]
at app.ticketme.securityconfig.UserManagmentConfig$$EnhancerBySpringCGLIB$$a7378581.CGLIB$authenticationManager$1(<generated>) ~[classes/:na]
at app.ticketme.securityconfig.UserManagmentConfig$$EnhancerBySpringCGLIB$$a7378581$$FastClassBySpringCGLIB$$2537ee3.invoke(<generated>) ~[classes/:na]
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.3.21.jar:5.3.21]
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:331) ~[spring-context-5.3.21.jar:5.3.21]
at app.ticketme.securityconfig.UserManagmentConfig$$EnhancerBySpringCGLIB$$a7378581.authenticationManager(<generated>) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.3.21.jar:5.3.21]
... 20 common frames omitted
Sadly, most of the youtube tutorials use the deprecated WebSecurityConfigurerAdapter, what am i doing wrong here ? any help appreciated.
when you enable formLogin, the framework will build a authentication manager for you with the supplied beans that you instantiate.
Why you are building your own authenticaation manager i have no idea.
So lets go through the steps, when you select you want to use formLogin the framework creates an authentication manager with the beans you have provided. You have provided a passwordEncoder and you should also provide an implementation of the UserDetailsService interface. This should be supplied like a bean as such:
#Bean
CustomUserDetailsService customUserDetailsService() {
return new CustomUserDetailsService();
}
Spring will then create a DaoAuthenticationProvider and stick your password encoder in it and your custom UserDetailsService.
And your error message tells me that since you have already built a generic provider, the framework cant add more stuff to it.
You should read how to enable form login in the documentation FormLogin Spring security
and basically remove:
#Bean
public AuthenticationManager authenticationManager(AuthenticationManagerBuilder builder) throws Exception {
return builder.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder())
.and()
.build();
}

thymeleaf error

Below code throw error of unresolvable circular reference. when Spring is trying to create bean of MessageFormatHelper class.This error throw while I run the jar. I try to see but not getting what is reason. Could anyone help.
First class,
#Component
class DbTemplateResolver extends TemplateResolver {
#Autowired
SpringTemplateEngine templateEngine;
....othercode
#PostConstruct
public void extension() {
templateEngine.addTemplateResolver(this);
}
...other code
}
Second class,
#Component
class MessageFormatHelper{
#Autowired
SpringTemplateEngine templateEngine;
... other code
String getMessage()
{
final Context ctx = new Context(locale);
ctx.setVariable("contractMap", model.get(ContractMap.TEMPLATE_MODEL_MAP_KEY));
mergedMessage = templateEngine.process(fileName, ctx);
}
}
Full error:
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.flex.eventManagement.handler.helper.MessageFormatHelper com.flex.eventManagement.handler.helper.NotificationPreProcessor.messageFormatHelper; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'messageFormatHelper': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.thymeleaf.spring4.SpringTemplateEngine com.flex.eventManagement.handler.helper.MessageFormatHelper.templateEngine; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$ThymeleafDefaultConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private final java.util.Collection org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$ThymeleafDefaultConfiguration.templateResolvers; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dbTemplateResolver': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.thymeleaf.spring4.SpringTemplateEngine com.flex.eventManagement.handler.helper.DbTemplateResolver.templateEngine; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'templateEngine': Requested bean is currently in creation: Is there an unresolvable circular reference?
Updated
Remove template engine auto-wire from DbTemplateResolver class. Autowire into MessageFormatHelper.java class like below
class MessageFormatHelper{
#Bean
public DbTemplateResolver dbTemplateResolver() {
DbTemplateResolver resolver = new DbTemplateResolver();
resolver.setOrder(2);
return resolver;
}
#Bean
public SpringTemplateEngine thymeleafTemplateEngine() {
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setTemplateResolvers(Sets.newHashSet(dbTemplateResolver()));
return engine;
}
}
Also I need to remove SpringTemplateEngine auto wired from MessageFormatHelper right? so how can I call mergedMessage = templateEngine.process(fileName, ctx);?
Update 2.
should followed required in MessageFormatHelper
#Autowired
DbTemplateResolver dbTemplateResolver;
#Autowired
SpringTemplateEngine templateEngine;
#PostConstruct
public void extension() {
templateEngine.addTemplateResolver(dbTemplateResolver);
}
Your code is flawed and it seems you lack basic understanding of how Spring works and how you should use Spring to configure things.
First you are using Spring Boot and want to use Thymeleaf. This is simply done by added the spring-boot-starter-thymeleaf as a dependency for you project. (I assume you have already done this).
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf<artifactId>
</dependency>
Spring Boot detects the fact that you have Thymeleaf on your classpath and the ThymeleafAutoConfiguration will kick in and configure the SpringTemplateEngine for you. It will even detect every bean of the type ITemplateResolver, which I assume your DbTemplateResolver implements.
The only thing to have your DbTemplateResolver add is to add a #Bean method to an #Configuration (or your application) class.
#Bean
public ITemplateResolver dbTemplateResolver() {
return new DbTemplateResolver();
}
Spring will detect it and inject it into the automatically configured SpringTemplateEngine.
The only thing you need to do is in classes you need the SpringTemplateEngine you need to auto wire it. Just use the super class not the concrete type.
#Autowired
private TemplateEngine templateEngine;
Don't mess around with trying to configure it later on, use the framework for that.

Disable Basic Authentication while using Spring Security Java configuration

I am trying to secure a web application using Spring Security java configuration.
This is how the configuration looks:-
#Configuration
#EnableWebMvcSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private String googleClientSecret;
#Autowired
private CustomUserService customUserService;
/*
* (non-Javadoc)
*
* #see org.springframework.security.config.annotation.web.configuration.
* WebSecurityConfigurerAdapter
* #configure(org.springframework.security.config
* .annotation.web.builders.HttpSecurity)
*/
#Override
protected void configure(HttpSecurity http) throws Exception {
// #formatter:off
http
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/","/static/**", "/resources/**","/resources/public/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic().disable()
.requiresChannel().anyRequest().requiresSecure();
// #formatter:on
super.configure(http);
}
#Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
// #formatter:off
auth
.eraseCredentials(true)
.userDetailsService(customUserService);
// #formatter:on
super.configure(auth);
}
}
Notice that I have explicitly disabled HTTP Basic authentication using:-
.httpBasic().disable()
I am still getting HTTP Authenticaton prompt box while accessing a secured url. Why?
Please help me fix this.
I just want to render the default login form that comes bundled.
Spring Boot Starter Version : 1.1.5
Spring Security Version : 3.2.5
Thanks
First of all, calling super.configure(http); will override whole your configuration you have before that.
Try this instead:
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic().disable();
In case you use Spring Boot, the documentation states:
To switch off the Boot default configuration completely in a web
application you can add a bean with #EnableWebSecurity
So if you want to fully customize itself that might be an option.
Just to make it clear... You just need to put #EnableWebSecurity annotation on your main application class or application configuration class.
You can disable the formLogin through the HttpSecurity instance as follow:
http.authorizeRequests().antMatchers("/public/**").permitAll()
.antMatchers("/api/**").hasRole("USER")
.anyRequest().authenticated()
.and().formLogin().disable();
This will lead receiving 403 Http error when trying to access any secured resource
Anonymous option worked for me. My code like
http.csrf().disable().headers().frameOptions().sameOrigin().and().
authorizeRequests().anyRequest().anonymous().and().httpBasic().disable();
Suitable for Spring Boot or folks using OAuth
#Profile("test")
#EnableWebSecurity
static class BasicWebSecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().anyRequest().anonymous().and().httpBasic().disable();
}
}
If you are using #EnableOAuth2Client or #EnableResourceServer, then in test profile switch to basic auth and then disable the same. In Spring Boot,to switch off the spring security default configuration completely in a web application you need to add a bean with #EnableWebSecurity
The following worked for me:
http
.authorizeRequests()
.anyRequest().permitAll();

Resources