Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a custom user logged via InMemoryAuthentication with Spring Security?

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 ?

like image 843
m4rtin Avatar asked Mar 21 '14 16:03

m4rtin


People also ask

What is inMemoryAuthentication in Spring Security?

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.


1 Answers

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.

like image 168
m4rtin Avatar answered Sep 21 '22 04:09

m4rtin