How to impersonate user using SwitchUserFilter in

2020-06-03 08:09发布

问题:

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 ?

回答1:

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

GET /login/impersonate?username=loginIdOfTheNewUser

and to switch back

GET /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.