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 ?
Impersonate a user Users or Contacts. Click the name of an individual user to view the detail page. Click the Impersonate link next to the user's name.
To impersonate another user, the impersonator selects the Impersonate icon on the far right of the Tab Bar and selects the user from the Impersonate drop-down list. To stop impersonating a user, the impersonator clicks the Impersonate icon and selects Stop Impersonate from the Impersonate drop-down list.
By default any user who is assigned the admin role on an instance should have access to the "Impersonate User" button as found in the user contextual pull-down menu. Selection of this option will then bring up the Impersonate User dialog for which various user types can be simulated for login into the instance.
Spring Security allows customizing HTTP security for features, such as endpoints authorization or the authentication manager configuration, by extending a WebSecurityConfigurerAdapter class.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With