Viktor Kurov
Viktor Kurov

Reputation: 13

User Impersonation with Spring Security

I am trying to implement a user impersonation using Spring Security and its SwitchUserFilter.

Currently the Configuration looks as follows:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers("/impersonate*").hasRole("Administrator");
    http.addFilter(switchUserFilter());
    super.configure(http);
    setLoginView(http, ViewLogin.class);
}
...
@Bean
public SwitchUserFilter switchUserFilter(){
    SwitchUserFilter filter = new SwitchUserFilter();
    filter.setUserDetailsService(userDetailsService);
    filter.setSwitchUserUrl("/impersonate");
    filter.setSwitchFailureUrl("/switchUser");
    filter.setTargetUrl("/");
    return filter;
}

And I was trying to navigate to the impersonation using:

UI.getCurrent().getPage().setLocation("/impersonate?username="+username);

Unfortunately Vaadin is trying to navigate to the page "/impersonate..." but doesn't find a corresponding Page and skips the SwitchUserFilter. How would I force the switch?

Upvotes: 1

Views: 1731

Answers (1)

cfrick
cfrick

Reputation: 37063

If you use setSwitchUserUrl it will match only POST requests [1]. But you want to use a GET request. So you have to use a matcher like this:

filter.setSwitchUserMatcher(new AntPathRequestMatcher("/impersonate", "GET"));

BTW: you don't have to addFilter the filter, if you define it as a @Bean.

[1] https://github.com/spring-projects/spring-security/blob/e125a76687d4ca9739cd663eedc107c7ff55e8cf/web/src/main/java/org/springframework/security/web/authentication/switchuser/SwitchUserFilter.java#L513-L515

Upvotes: 4

Related Questions