goldthelocks
goldthelocks

Reputation: 173

List users in memory in Spring Security?

Or more specifically, is it possible?

We currently have our users in memory using XML configuration. We know of InMemoryUserDetailsManager, but unfortunately it's not possible to get all users and users map inside InMemoryUserDetailsManager is private.

Upvotes: 2

Views: 1620

Answers (1)

Shailendra
Shailendra

Reputation: 9102

Yes you can actually access that using a bit a jugglery with Java reflection where you can access the properties which are not exposed via public API. I have used below the RelectionUtils from Spring which should be available if you are using Spring ( which you are since it's Spring security). The key is to get hold of AuthenticationManager via Autowiring and then drill down to the required Map containing the user info.

Just to demonstrate I have tested this on Spring Boot App but there should not be any issue if your are not using it.

@SpringBootApplication
public class SpringBootSecurityInMemoryApplication implements CommandLineRunner {

     @Autowired AuthenticationManager authenticationManager;

................................
...............................
public static void main(String[] args) {
        SpringApplication.run(SpringBootSecurityInMemoryApplication.class, args);
    }

@Override
    public void run(String... args) throws Exception {      
        introspectBean(authenticationManager);


    }

public void printUsersMap(Object bean){

        Field field = ReflectionUtils.findField(org.springframework.security.authentication.ProviderManager.class, "providers");
        ReflectionUtils.makeAccessible(field);
        List listOfProviders = (List)ReflectionUtils.getField(field, bean);     
        DaoAuthenticationProvider dao = (DaoAuthenticationProvider)listOfProviders.get(0);
        Field fieldUserDetailService = ReflectionUtils.findField(DaoAuthenticationProvider.class, "userDetailsService");
        ReflectionUtils.makeAccessible(fieldUserDetailService);
        InMemoryUserDetailsManager userDet = (InMemoryUserDetailsManager)(ReflectionUtils.getField(fieldUserDetailService, dao));
        Field usersMapField = ReflectionUtils.findField(InMemoryUserDetailsManager.class, "users");
        ReflectionUtils.makeAccessible(usersMapField);
        Map map = (Map)ReflectionUtils.getField(usersMapField, userDet);
        System.out.println(map);

    }

I have 2 users configured - shailendra and admin. You can see the output of program below. You can get the required info from this map.

{shailendra=org.springframework.security.provisioning.MutableUser@245a060f, admin=org.springframework.security.provisioning.MutableUser@6edaa77a}

Upvotes: 1

Related Questions