I have a Spring MVC web app secured with Spring Security and I'm in the process of writing tests. I'm struggling with getting one of my (custom) user retrieved by Spring Security in its SecurityContextHolder. Once my user is "inserted" (java-configured) with :
auth.inMemoryAuthentication().getUserDetailsService().createUser(myCustomUser);
I can then create the related token (a UsernamePasswordAuthenticationToken) and ask for Spring to authenticate my user with this token. The problem is Spring doesn't retrieve a custom user instance but an instance of its User class. When Spring looks for such a user in the following method (from Spring's InMemoryUserDetailsManager) :
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserDetails user = users.get(username.toLowerCase());
if (user == null) {
throw new UsernameNotFoundException(username);
}
return new User(user.getUsername(), user.getPassword(), user.isEnabled(), user.isAccountNonExpired(),
user.isCredentialsNonExpired(), user.isAccountNonLocked(), user.getAuthorities());
}
It instantiates a new User with the details provided by my configuration.
I don't see the problem with having the InMemoryUserDetailsManager directly returning what was sent to him via the "getUserDetailsService().createUser" call but there must be one probably... Anyway, I'm probably doing something wrong here, any idea ?
inMemoryAuthentication() is the method of AuthenticationManagerBuilder class is used to perform in-memory authentication in the Spring Security. This method is used for creating the user with respective roles and passwords.
Like suggested, I ended up writing a custom InMemoryUserDetailsManager
which I feed my Spring Security configuration with.
To anyone wondering, it seems that it's the only way.
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