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.