Menu

Spring REST endpoint to impersonate

Goal

Expose a REST endpoint to permit a user to impersonate other user in a Spring application

Description

In one of the projects I worked recently, we had a Spring based application exposing REST services that were consumed by an AngularJS client (that part, however, is not relevant for this specific recipe but it’s just to put the example into the appropriate context).

And in that project, there are some requirements regarding the impersonation of users. Notice that I decided not to use the SwitchUserFilter from Spring itself but to mimic its code in my own REST service, because of the security requirement stated below and also because I wanted to provide the client interface with a JSON answer regarding the impersonation answer):

Auditing – operations that are performed on behalf of someone should be marked as such, in the format as

Security – only authorized users are allowed to represent someone, i.e., in this project, if one wants to be impersonated by someone, s/he must create a delegation record on the database, giving permissions for a user to impersonate her/him during a specific period in time

This recipe details the basic steps of the implementation I made in order to achieve this result.

How to

Create an audit filter to filter the requests and put in context the appropriate username (we are using Hibernate envers for auditing the changes in the persistent domain model. Notice, however, that I won’t go into the details of the Hibernate envers auditing within the project because that is not the focus of this recipe):

The security constraint implementation will not be shown in this recipe as I plan to add a new one containing the details on how to define your own Spring permission evaluator and how to implement the stated requirements as well as how to expose the details of the currently logged in user for the client application to be consumed as a REST service.

To impersonate some user, we should access the endpoint /impersonate/login/?username=<some user> and to get back to the original user, if one is impersonating some user, /impersonate/logout.

Explanations

This implementation is all based on Spring security, namely the class SwitchUserFilter but exposed as a REST endpoint to be able to return a JSON object through a REST call and to be able to add specific security constraints implemented with something like hasPermission, instead of securing the URL for a specific role or roles with hasRole like access control rule.