In JUnit tests with Spring MockMVC, there are two methods for authenticating as a Spring Security user: @WithMockUser
creates a dummy user with the provided credentials, @WithUserDetails
takes a user's name and resolves it to the correct custom UserDetails
implementation with a custom UserDetailsService
(the UserDetailsServiceImpl
).
In my case, the UserDetailsService
loads an user from the database. The user I want to use was inserted in the @Before
method of the test suite.
However, my UserDetailsServiceImpl
does not find the user.
In my @Before
, I insert the user like this:
User u = new User();
u.setEMail("[email protected]");
u = userRepository.save(u);
And in the UserDetailsServiceImpl
:
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = this.userRepository.findOneByEMail(username);
if (user == null)
throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username));
return user;
}
How can I use an account created in @Before
with @WithUserDetails
?
As of Spring Security version 5.7. 1, the default username is user and the password is randomly generated and displayed in the console (e.g. 8e557245-73e2-4286-969a-ff57fe326336 ).
Spring security secures all HTTP endpoints by default. A user has to login in a default HTTP form. To enable Spring Boot security, we add spring-boot-starter-security to the dependencies.
Unfortunately, you can't do easily @WithUserDetails
with @Before
, because Spring @WithUserDetails
annotation will invoke Spring security context test listener before running setUp
method with @Before
.
Here is https://stackoverflow.com/a/38282258/1814524 a little trick and answer to your question.
You can use @PostConstruct
instead of @Before
. That did the trick for me. Can anybody confirm that?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With