How to temporarily change the role provided to achieve "viewing the site as" someone else "

We are using 2.x spring protection right now. I will be asked to create an administrative tool so that ROLE_ADMIN can change to any user on the site and view the site as that person (each person on the site can see different things depending on the role, which is a dynamically provided database in the database) and, of course, the administrator must be able to return to the administrator without logging in.

Is there a built-in function, if not, how do I do this?

Thanks in advance!

+1
source share
2 answers

I do not know any spring-security ready-made solution that will answer your requirement, but I can offer you a way to implement it.

  • Declare the URL for the "view site as" action with a request parameter to get the username, for example: /myApp/viewTheSiteAs?user=marley

  • Write your own filter that will do the following:
    2.1. Verify that the authenticated user is admin
    2.2 Remove the user from the action ("marley" :-))
    2.3 Confirm that it exists (using UserDetailsService).
    2.4 Create a new authenticated authentication object that is appropriate for the user you retrieved and replace the current authentication object with your own object: SecurityContextHolder.getContext().setAuthentication(myNewAuthObject)

  • Add a filter chain to the spring security configuration file for / ViewTheSiteAs, which will act as a regular filter chain (should be authenticated as a "real" user as normal) and find your custom filter at the end of the chain.

Performing the following action will cause spring protection to consider that the user from the viewTheSiteAs action is authenticated, and thereby checks the access rights for this user.

ps is not a security break because it lowers the rights of authenticated users, which means a "less powerful" user.

Good luck.

+2
source

Source: https://habr.com/ru/post/903604/


All Articles