Package org.springframework.security.web.authentication.switchuser

# Class SwitchUserFilter

java.lang.Object
org.springframework.web.filter.GenericFilterBean
org.springframework.security.web.authentication.switchuser.SwitchUserFilter

All Implemented Interfaces:
  `jakarta.servlet.Filter`, `org.springframework.beans.factory.Aware`, `org.springframework.beans.factory.BeanNameAware`, `org.springframework.beans.factory.DisposableBean`, `org.springframework.beans.factory.InitializingBean`, `org.springframework.context.ApplicationEventPublisherAware`, `org.springframework.context.EnvironmentAware`, `org.springframework.context.MessageSourceAware`, `org.springframework.core.env.EnvironmentCapable`, `org.springframework.web.context.ServletContextAware`

public class SwitchUserFilter extends org.springframework.web.filter.GenericFilterBean implements org.springframework.context.ApplicationEventPublisherAware, org.springframework.context.MessageSourceAware
Switch User processing filter responsible for user context switching.

This filter is similar to Unix 'su' however for Spring Security-managed web applications. A common use-case for this feature is the ability to allow higher-authority users (e.g. ROLE_ADMIN) to switch to a regular user (e.g. ROLE_USER).

This filter assumes that the user performing the switch will be required to be logged in as normal (i.e. as a ROLE_ADMIN user). The user will then access a page/controller that enables the administrator to specify who they wish to become (see `switchUserUrl`).

Note: This URL will be required to have appropriate security constraints configured so that only users of that role can access it (e.g. ROLE_ADMIN).

On a successful switch, the user's `SecurityContext` will be updated to reflect the specified user and will also contain an additional `SwitchUserGrantedAuthority` which contains the original user. Before switching, a check will be made on whether the user is already currently switched, and any current switch will be exited to prevent "nested" switches.

To 'exit' from a user context, the user needs to access a URL (see `exitUserUrl`) that will switch back to the original user as identified by the `ROLE_PREVIOUS_ADMINISTRATOR`.

To configure the Switch User Processing Filter, create a bean definition for the Switch User processing filter and add to the filterChainProxy. Note that the filter must come after the `FilterSecurityInteceptor` in the chain, in order to apply the correct constraints to the `switchUserUrl`. Example:

     <bean id="switchUserProcessingFilter" class="org.springframework.security.web.authentication.switchuser.SwitchUserFilter">
        <property name="userDetailsService" ref="userDetailsService" />
        <property name="switchUserUrl" value="/login/impersonate" />
        <property name="exitUserUrl" value="/logout/impersonate" />
        <property name="targetUrl" value="/index.jsp" />
     </bean>

See Also:
  - `SwitchUserGrantedAuthority`

## Field Summary

Fields
Modifier and Type
Field
Description
`protected org.springframework.context.support.MessageSourceAccessor`
`messages`
`static final String`
`ROLE_PREVIOUS_ADMINISTRATOR`
`static final String`
`SPRING_SECURITY_SWITCH_USERNAME_KEY`

### Fields inherited from class org.springframework.web.filter.GenericFilterBean

`logger`

## Constructor Summary

Constructors
Constructor
Description
`SwitchUserFilter()`

## Method Summary

Modifier and Type
Method
Description
`void`
`afterPropertiesSet()`
`protected org.springframework.security.core.Authentication`
`attemptExitUser(jakarta.servlet.http.HttpServletRequest request)`
Attempt to exit from an already switched user.
`protected org.springframework.security.core.Authentication`
`attemptSwitchUser(jakarta.servlet.http.HttpServletRequest request)`
Attempt to switch to another user.
`void`
`doFilter(jakarta.servlet.ServletRequest request, jakarta.servlet.ServletResponse response, jakarta.servlet.FilterChain chain)`
`protected boolean`
`requiresExitUser(jakarta.servlet.http.HttpServletRequest request)`
Checks the request URI for the presence of `exitUserUrl`.
`protected boolean`
`requiresSwitchUser(jakarta.servlet.http.HttpServletRequest request)`
Checks the request URI for the presence of `switchUserUrl`.
`void`
`setApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher eventPublisher)`
`void`
`setAuthenticationDetailsSource(org.springframework.security.authentication.AuthenticationDetailsSource<jakarta.servlet.http.HttpServletRequest,?> authenticationDetailsSource)`
`void`
`setExitUserMatcher(RequestMatcher exitUserMatcher)`
Set the matcher to respond to exit user processing.
`void`
`setExitUserUrl(String exitUserUrl)`
Set the URL to respond to exit user processing.
`void`
`setFailureHandler(AuthenticationFailureHandler failureHandler)`
Used to define custom behaviour when a switch fails.
`void`
`setMessageSource(org.springframework.context.MessageSource messageSource)`
`void`
`setSecurityContextHolderStrategy(org.springframework.security.core.context.SecurityContextHolderStrategy securityContextHolderStrategy)`
Sets the `SecurityContextHolderStrategy` to use.
`void`
`setSecurityContextRepository(SecurityContextRepository securityContextRepository)`
Sets the `SecurityContextRepository` to save the `SecurityContext` on switch user success.
`void`
`setSuccessHandler(AuthenticationSuccessHandler successHandler)`
Used to define custom behaviour on a successful switch or exit user.
`void`
`setSwitchAuthorityRole(String switchAuthorityRole)`
Allows the role of the switchAuthority to be customized.
`void`
`setSwitchFailureUrl(String switchFailureUrl)`
Sets the URL to which a user should be redirected if the switch fails.
`void`
`setSwitchUserAuthorityChanger(SwitchUserAuthorityChanger switchUserAuthorityChanger)`
`void`
`setSwitchUserMatcher(RequestMatcher switchUserMatcher)`
Set the matcher to respond to switch user processing.
`void`
`setSwitchUserUrl(String switchUserUrl)`
Set the URL to respond to switch user processing.
`void`
`setTargetUrl(String targetUrl)`
Sets the URL to go to after a successful switch / exit user request.
`void`
`setUserDetailsChecker(org.springframework.security.core.userdetails.UserDetailsChecker userDetailsChecker)`
Sets the `UserDetailsChecker` that is called on the target user whenever the user is switched.
`void`
`setUserDetailsService(org.springframework.security.core.userdetails.UserDetailsService userDetailsService)`
Sets the authentication data access object.
`void`
`setUsernameParameter(String usernameParameter)`
Allows the parameter containing the username to be customized.

### Methods inherited from class org.springframework.web.filter.GenericFilterBean

`addRequiredProperty, createEnvironment, destroy, getEnvironment, getFilterConfig, getFilterName, getServletContext, init, initBeanWrapper, initFilterBean, setBeanName, setEnvironment, setServletContext`

### Methods inherited from class java.lang.Object

`clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`

## Field Details

### SPRING_SECURITY_SWITCH_USERNAME_KEY

public static final String SPRING_SECURITY_SWITCH_USERNAME_KEY

See Also:
  - Constant Field Values

### ROLE_PREVIOUS_ADMINISTRATOR

public static final String ROLE_PREVIOUS_ADMINISTRATOR

See Also:
  - Constant Field Values

### messages

protected org.springframework.context.support.MessageSourceAccessor messages

## Constructor Details

### SwitchUserFilter

public SwitchUserFilter()

## Method Details

### afterPropertiesSet

public void afterPropertiesSet()

Specified by:
  `afterPropertiesSet` in interface `org.springframework.beans.factory.InitializingBean`
Overrides:
  `afterPropertiesSet` in class `org.springframework.web.filter.GenericFilterBean`

### doFilter

public void doFilter(jakarta.servlet.ServletRequest request, jakarta.servlet.ServletResponse response, jakarta.servlet.FilterChain chain) throws IOException, jakarta.servlet.ServletException

Specified by:
  `doFilter` in interface `jakarta.servlet.Filter`
Throws:
  `IOException`
  `jakarta.servlet.ServletException`

### attemptSwitchUser

protected org.springframework.security.core.Authentication attemptSwitchUser(jakarta.servlet.http.HttpServletRequest request) throws org.springframework.security.core.AuthenticationException
Attempt to switch to another user. If the user does not exist or is not active, return null.

Returns:
  The new `Authentication` request if successfully switched to another user, `null` otherwise.
Throws:
  `org.springframework.security.core.userdetails.UsernameNotFoundException` - If the target user is not found.
  `org.springframework.security.authentication.LockedException` - if the account is locked.
  `org.springframework.security.authentication.DisabledException` - If the target user is disabled.
  `org.springframework.security.authentication.AccountExpiredException` - If the target user account is expired.
  `org.springframework.security.authentication.CredentialsExpiredException` - If the target user credentials are expired.
  `org.springframework.security.core.AuthenticationException`

### attemptExitUser

protected org.springframework.security.core.Authentication attemptExitUser(jakarta.servlet.http.HttpServletRequest request) throws org.springframework.security.authentication.AuthenticationCredentialsNotFoundException
Attempt to exit from an already switched user.

Parameters:
  `request` - The http servlet request
Returns:
  The original `Authentication` object or `null` otherwise.
Throws:
  `org.springframework.security.authentication.AuthenticationCredentialsNotFoundException` - If no `Authentication` associated with this request.

### requiresExitUser

protected boolean requiresExitUser(jakarta.servlet.http.HttpServletRequest request)
Checks the request URI for the presence of `exitUserUrl`.

Parameters:
  `request` - The http servlet request
Returns:
  `true` if the request requires a exit user, `false` otherwise.
See Also:
  - `setExitUserUrl(String)`

### requiresSwitchUser

protected boolean requiresSwitchUser(jakarta.servlet.http.HttpServletRequest request)
Checks the request URI for the presence of `switchUserUrl`.

Parameters:
  `request` - The http servlet request
Returns:
  `true` if the request requires a switch, `false` otherwise.
See Also:
  - `setSwitchUserUrl(String)`

### setApplicationEventPublisher

public void setApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher eventPublisher) throws org.springframework.beans.BeansException

Specified by:
  `setApplicationEventPublisher` in interface `org.springframework.context.ApplicationEventPublisherAware`
Throws:
  `org.springframework.beans.BeansException`

### setAuthenticationDetailsSource

public void setAuthenticationDetailsSource(org.springframework.security.authentication.AuthenticationDetailsSource<jakarta.servlet.http.HttpServletRequest,?> authenticationDetailsSource)

### setMessageSource

public void setMessageSource(org.springframework.context.MessageSource messageSource)

Specified by:
  `setMessageSource` in interface `org.springframework.context.MessageSourceAware`

### setUserDetailsService

public void setUserDetailsService(org.springframework.security.core.userdetails.UserDetailsService userDetailsService)
Sets the authentication data access object.

Parameters:
  `userDetailsService` - The `UserDetailsService` which will be used to load information for the user that is being switched to.

### setExitUserUrl

public void setExitUserUrl(String exitUserUrl)
Set the URL to respond to exit user processing. This is a shortcut for `setExitUserMatcher(RequestMatcher)`.

Parameters:
  `exitUserUrl` - The exit user URL.

### setExitUserMatcher

public void setExitUserMatcher(RequestMatcher exitUserMatcher)
Set the matcher to respond to exit user processing.

Parameters:
  `exitUserMatcher` - The exit matcher to use.

### setSwitchUserUrl

public void setSwitchUserUrl(String switchUserUrl)
Set the URL to respond to switch user processing. This is a shortcut for `setSwitchUserMatcher(RequestMatcher)`

Parameters:
  `switchUserUrl` - The switch user URL.

### setSwitchUserMatcher

public void setSwitchUserMatcher(RequestMatcher switchUserMatcher)
Set the matcher to respond to switch user processing.

Parameters:
  `switchUserMatcher` - The switch user matcher.

### setTargetUrl

public void setTargetUrl(String targetUrl)
Sets the URL to go to after a successful switch / exit user request. Use `setSuccessHandler` instead if you need more customized behaviour.

Parameters:
  `targetUrl` - The target url.

### setSuccessHandler

public void setSuccessHandler(AuthenticationSuccessHandler successHandler)
Used to define custom behaviour on a successful switch or exit user.

Can be used instead of setting `targetUrl`.

### setSwitchFailureUrl

public void setSwitchFailureUrl(String switchFailureUrl)
Sets the URL to which a user should be redirected if the switch fails. For example, this might happen because the account they are attempting to switch to is invalid (the user doesn't exist, account is locked etc).

If not set, an error message will be written to the response.

Use `failureHandler` instead if you need more customized behaviour.

Parameters:
  `switchFailureUrl` - the url to redirect to.

### setFailureHandler

public void setFailureHandler(AuthenticationFailureHandler failureHandler)
Used to define custom behaviour when a switch fails.

Can be used instead of setting `switchFailureUrl`.

### setSwitchUserAuthorityChanger

public void setSwitchUserAuthorityChanger(SwitchUserAuthorityChanger switchUserAuthorityChanger)

Parameters:
  `switchUserAuthorityChanger` - to use to fine-tune the authorities granted to subclasses (may be null if SwitchUserFilter should not fine-tune the authorities)

### setUserDetailsChecker

public void setUserDetailsChecker(org.springframework.security.core.userdetails.UserDetailsChecker userDetailsChecker)
Sets the `UserDetailsChecker` that is called on the target user whenever the user is switched.

Parameters:
  `userDetailsChecker` - the `UserDetailsChecker` that checks the status of the user that is being switched to. Defaults to `AccountStatusUserDetailsChecker`.

### setUsernameParameter

public void setUsernameParameter(String usernameParameter)
Allows the parameter containing the username to be customized.

Parameters:
  `usernameParameter` - the parameter name. Defaults to `username`

### setSwitchAuthorityRole

public void setSwitchAuthorityRole(String switchAuthorityRole)
Allows the role of the switchAuthority to be customized.

Parameters:
  `switchAuthorityRole` - the role name. Defaults to `ROLE_PREVIOUS_ADMINISTRATOR`

### setSecurityContextHolderStrategy

public void setSecurityContextHolderStrategy(org.springframework.security.core.context.SecurityContextHolderStrategy securityContextHolderStrategy)
Sets the `SecurityContextHolderStrategy` to use. The default action is to use the `SecurityContextHolderStrategy` stored in `SecurityContextHolder`.

Since:
  5.8

### setSecurityContextRepository

public void setSecurityContextRepository(SecurityContextRepository securityContextRepository)
Sets the `SecurityContextRepository` to save the `SecurityContext` on switch user success. The default is `RequestAttributeSecurityContextRepository`.

Parameters:
  `securityContextRepository` - the `SecurityContextRepository` to use. Cannot be null.
Since:
  5.7.7