-
Notifications
You must be signed in to change notification settings - Fork 6.2k
Honor @Primary for UserDetailsService and UserDetailsPasswordService in InitializeUserDetailsBeanManagerConfigurer #18015
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
siva-sai-udaygiri
wants to merge
4
commits into
spring-projects:main
Choose a base branch
from
siva-sai-udaygiri:honor-primary-uds-17902
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+199
−36
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
57588c4
Honor @Primary for UserDetailsService and UserDetailsPasswordService
siva-sai-udaygiri 27574ee
Polish UserDetailsService Selection Logic
jzheaux 581d666
Reduce Comments
jzheaux 829cac4
Honor @Primary for UserDetailsService and UserDetailsPasswordService …
siva-sai-udaygiri File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
146 changes: 146 additions & 0 deletions
146
...otation/authentication/configuration/InitializeUserDetailsBeanManagerConfigurerTests.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,146 @@ | ||
| /* | ||
| * Copyright 2004-present the original author or authors. | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * https://www.apache.org/licenses/LICENSE-2.0 | ||
| */ | ||
|
|
||
| package org.springframework.security.config.annotation.authentication.configuration; | ||
|
|
||
| import java.util.List; | ||
|
|
||
| import org.junit.jupiter.api.Test; | ||
|
|
||
| import org.springframework.beans.factory.ObjectProvider; | ||
| import org.springframework.context.ApplicationContext; | ||
| import org.springframework.security.authentication.AuthenticationManager; | ||
| import org.springframework.security.authentication.ProviderManager; | ||
| import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; | ||
| import org.springframework.security.authentication.password.CompromisedPasswordChecker; | ||
| import org.springframework.security.config.ObjectPostProcessor; | ||
| import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; | ||
| import org.springframework.security.core.userdetails.User; | ||
| import org.springframework.security.core.userdetails.UserDetailsPasswordService; | ||
| import org.springframework.security.core.userdetails.UserDetailsService; | ||
| import org.springframework.security.crypto.factory.PasswordEncoderFactories; | ||
| import org.springframework.security.crypto.password.PasswordEncoder; | ||
| import org.springframework.security.provisioning.InMemoryUserDetailsManager; | ||
|
|
||
| import static org.assertj.core.api.Assertions.assertThat; | ||
| import static org.mockito.BDDMockito.given; | ||
| import static org.mockito.Mockito.mock; | ||
|
|
||
| class InitializeUserDetailsBeanManagerConfigurerTests { | ||
|
|
||
| private static ObjectPostProcessor<Object> opp() { | ||
| return new ObjectPostProcessor<>() { | ||
| @Override | ||
| public <O> O postProcess(O object) { return object; } | ||
| }; | ||
| } | ||
|
|
||
| @SuppressWarnings("unchecked") | ||
| @Test | ||
| void whenMultipleUdsAndOneResolvableCandidate_thenPrimaryIsAutoWired() throws Exception { | ||
| ApplicationContext ctx = mock(ApplicationContext.class); | ||
| given(ctx.getBeanNamesForType(UserDetailsService.class)).willReturn(new String[] { "udsA", "udsB" }); | ||
|
|
||
| PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder(); | ||
|
|
||
| InMemoryUserDetailsManager primary = new InMemoryUserDetailsManager( | ||
| User.withUsername("alice").passwordEncoder(encoder::encode).password("pw").roles("USER").build()); | ||
| InMemoryUserDetailsManager secondary = new InMemoryUserDetailsManager(); | ||
|
|
||
| ObjectProvider<UserDetailsService> udsProvider = | ||
| (ObjectProvider<UserDetailsService>) mock(ObjectProvider.class); | ||
| given(ctx.getBeanProvider(UserDetailsService.class)).willReturn(udsProvider); | ||
| given(udsProvider.getIfAvailable()).willReturn(primary); // container picks single candidate | ||
|
|
||
| // resolveBeanName(..) path | ||
| given(ctx.getBean("udsA")).willReturn(secondary); | ||
| given(ctx.getBean("udsB")).willReturn(primary); | ||
|
|
||
| ObjectProvider<PasswordEncoder> peProvider = | ||
| (ObjectProvider<PasswordEncoder>) mock(ObjectProvider.class); | ||
| given(ctx.getBeanProvider(PasswordEncoder.class)).willReturn(peProvider); | ||
| given(peProvider.getIfUnique()).willReturn(encoder); | ||
|
|
||
| // Stub optional providers to avoid NPEs | ||
| ObjectProvider<UserDetailsPasswordService> udpsProvider = | ||
| (ObjectProvider<UserDetailsPasswordService>) mock(ObjectProvider.class); | ||
| given(ctx.getBeanProvider(UserDetailsPasswordService.class)).willReturn(udpsProvider); | ||
| given(udpsProvider.getIfAvailable()).willReturn(null); | ||
|
|
||
| ObjectProvider<CompromisedPasswordChecker> cpcProvider = | ||
| (ObjectProvider<CompromisedPasswordChecker>) mock(ObjectProvider.class); | ||
| given(ctx.getBeanProvider(CompromisedPasswordChecker.class)).willReturn(cpcProvider); | ||
| given(cpcProvider.getIfUnique()).willReturn(null); | ||
|
|
||
| AuthenticationManagerBuilder builder = new AuthenticationManagerBuilder(opp()); | ||
| new InitializeUserDetailsBeanManagerConfigurer(ctx) | ||
| .new InitializeUserDetailsManagerConfigurer() | ||
| .configure(builder); | ||
|
|
||
| AuthenticationManager manager = builder.build(); | ||
|
|
||
| // DaoAuthenticationProvider registered | ||
| assertThat(manager).isInstanceOf(ProviderManager.class); | ||
| List<?> providers = ((ProviderManager) manager).getProviders(); | ||
| assertThat(providers) | ||
| .anySatisfy((p) -> assertThat(p.getClass().getSimpleName()).isEqualTo("DaoAuthenticationProvider")); | ||
|
|
||
| // Auth works with the primary UDS + encoder | ||
| var auth = manager.authenticate(new UsernamePasswordAuthenticationToken("alice", "pw")); | ||
| assertThat(auth.isAuthenticated()).isTrue(); | ||
| } | ||
|
|
||
| @SuppressWarnings("unchecked") | ||
| @Test | ||
| void whenMultipleUdsAndNoSingleCandidate_thenSkipAutoWiring() throws Exception { | ||
| ApplicationContext ctx = mock(ApplicationContext.class); | ||
| given(ctx.getBeanNamesForType(UserDetailsService.class)).willReturn(new String[] { "udsA", "udsB" }); | ||
|
|
||
| ObjectProvider<UserDetailsService> udsProvider = | ||
| (ObjectProvider<UserDetailsService>) mock(ObjectProvider.class); | ||
| given(ctx.getBeanProvider(UserDetailsService.class)).willReturn(udsProvider); | ||
| given(udsProvider.getIfAvailable()).willReturn(null); // ambiguous → no single candidate | ||
|
|
||
| // Also stub other providers to null | ||
| ObjectProvider<PasswordEncoder> peProvider = | ||
| (ObjectProvider<PasswordEncoder>) mock(ObjectProvider.class); | ||
| given(ctx.getBeanProvider(PasswordEncoder.class)).willReturn(peProvider); | ||
| given(peProvider.getIfUnique()).willReturn(null); | ||
|
|
||
| ObjectProvider<UserDetailsPasswordService> udpsProvider = | ||
| (ObjectProvider<UserDetailsPasswordService>) mock(ObjectProvider.class); | ||
| given(ctx.getBeanProvider(UserDetailsPasswordService.class)).willReturn(udpsProvider); | ||
| given(udpsProvider.getIfAvailable()).willReturn(null); | ||
|
|
||
| ObjectProvider<CompromisedPasswordChecker> cpcProvider = | ||
| (ObjectProvider<CompromisedPasswordChecker>) mock(ObjectProvider.class); | ||
| given(ctx.getBeanProvider(CompromisedPasswordChecker.class)).willReturn(cpcProvider); | ||
| given(cpcProvider.getIfUnique()).willReturn(null); | ||
|
|
||
| AuthenticationManagerBuilder builder = new AuthenticationManagerBuilder(opp()); | ||
| new InitializeUserDetailsBeanManagerConfigurer(ctx) | ||
| .new InitializeUserDetailsManagerConfigurer() | ||
| .configure(builder); | ||
|
|
||
| AuthenticationManager manager = builder.build(); | ||
|
|
||
| // Success condition: nothing auto-registered. | ||
| if (manager == null) { | ||
| assertThat(manager).isNull(); | ||
| } | ||
| else if (manager instanceof ProviderManager pm) { | ||
| assertThat(pm.getProviders()) | ||
| .noneMatch((p) -> p.getClass().getSimpleName().equals("DaoAuthenticationProvider")); | ||
| } | ||
| else { | ||
| assertThat(manager.getClass().getSimpleName()).isNotEqualTo("ProviderManager"); | ||
| } | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I believe this changes the existing semantics by calling
getIfAvailableinstead ofgetIfUnique. TheObjectProviderJavaDoc implies that it accounts for@Primary:Can you confirm with unit tests that changing to
getIfAvailableis necessary to support@Primary?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks, @jzheaux! I added unit tests to show why we need to rely on the container’s autowire-candidate resolution to honor @primary.
• With getIfUnique(...) when there are two UserDetailsService beans and one is @primary, it still returns null (multiple names), so the global AuthenticationManager isn’t configured.
• With getIfAvailable(...) it delegates to autowire-candidate selection (same as normal injection), so the @primary bean is chosen, and the AuthenticationManager is configured.
New tests:
Location: spring-security-config/src/test/java/org/springframework/security/config/annotation/authentication/configuration/InitializeUserDetailsBeanManagerConfigurerTests.java
This keeps behavior the same for the single-bean case, and for multiple beans without a single resolvable candidate we still skip auto-wiring (and log). Please take another look and let me know if you’d prefer a different approach.