How to impersonate user using SwitchUserFilter in Spring?

Sachi-17 picture Sachi-17 · Jul 13, 2015 · Viewed 8.2k times · Source

I do not have knowledge on Spring Impersonating user.

I have gone through some sample code of configuration for impersonating user and noticed that SwitchUserFilter is used for this implementation.

How to implement impersonate user using Spring SwitchUserFilter Filter and how does it works ? What is the internal flow of impersonating user ?

In my application I am using spring security also.

Can anyone please help me with simple description or any sample example to achieve this ?

Answer

Sanjay picture Sanjay · Jul 15, 2015

You first need to create an instance of SwitchUserFilter, like this:

@Bean
public SwitchUserFilter switchUserFilter() {
    SwitchUserFilter filter = new SwitchUserFilter();
    filter.setUserDetailsService(userDetailsService);
    filter.setSuccessHandler(authenticationSuccessHandler);
    filter.setFailureHandler(authenticationFailureHandler());
    return filter;
}

Then, you can add the filter this way:

@Override
protected void configure(HttpSecurity http) throws Exception {

    http
     ...
     .addFilterAfter(switchUserFilter(), FilterSecurityInterceptor.class);

Now, to switch, you can use

POST /login/impersonate?username=loginIdOfTheNewUser

and to switch back

POST /logout/impersonate

Note that it’s your job to ensure that existing user must have enough rights for the switch. A common practice could be to restrict /login/impersonate only to ADMINs, and and /logout/impersonate to authenticated users, like this:

        .authorizeRequests()
            .antMatchers("/login/impersonate*").hasRole("ADMIN")
            .antMatchers("/logout/impersonate*").authenticated()
            .antMatchers("/**").permitAll();

See this for a complete example.