spring-security icon indicating copy to clipboard operation
spring-security copied to clipboard

oauth2Login DSL fails when passing a `SecurityContextRepository`

Open marcusdacoregio opened this issue 11 months ago • 1 comments

Describe the bug

Hi team ❤ , I'm trying to set the SecurityContextRepository configured by the oauth2Login() DSL and it fails with:

Caused by: java.lang.NullPointerException: Cannot invoke "org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.setSecurityContextRepository(org.springframework.security.web.context.SecurityContextRepository)" because "this.authFilter" is null
	at org.springframework.security.config.annotation.web.configurers.AbstractAuthenticationFilterConfigurer.securityContextRepository(AbstractAuthenticationFilterConfigurer.java:149) ~[spring-security-config-6.4.2.jar:6.4.2]
	at com.dooall.oauth2loginbug.Oauth2LoginBugApplication.lambda$filterChain$0(Oauth2LoginBugApplication.java:20) ~[main/:na]
	at org.springframework.security.config.annotation.web.builders.HttpSecurity.oauth2Login(HttpSecurity.java:2857) ~[spring-security-config-6.4.2.jar:6.4.2]
	at com.dooall.oauth2loginbug.Oauth2LoginBugApplication.filterChain(Oauth2LoginBugApplication.java:19) ~[main/:na]

I couldn't find any older issue related to this. The authFilter from AbstractAuthenticationFilterConfigurer is only instantiated at the OAuth2LoginConfigurer#init method, but setSecurityContextRepository is called before init. The current workaround is to add a ObjectPostProcessor:

.addObjectPostProcessor(new ObjectPostProcessor<OAuth2LoginAuthenticationFilter>() {
	@Override
	public <O extends OAuth2LoginAuthenticationFilter> O postProcess(O filter) {
		filter.setSecurityContextRepository(new NullSecurityContextRepository());
		return filter;
	}
})

To Reproduce Clone the sample application and run it.

Expected behavior The DSL should accept the provided SecurityContextRepository

Sample

https://github.com/marcusdacoregio/oauth2-login-bug

marcusdacoregio avatar Feb 19 '25 23:02 marcusdacoregio

Hi @marcusdacoregio ! I hope you're doing well 👍

I'm catching up with issues just now and saw this. Are you still having this issue?

jgrandja avatar Jun 11 '25 19:06 jgrandja

Yep, I've opened a PR to fix it https://github.com/spring-projects/spring-security/pull/17502

marcusdacoregio avatar Jul 09 '25 22:07 marcusdacoregio