Salesforce: How to detect "Impersonation" through code?

Hello Guys, I got a business requirement to implement for one of my client, they wanted me to prevent their application's access for impersonated user. They have a third party app integrated in Salesforce using canvas.

In order to implement this, I have to detect impersonated user and pass it to their server through canvas so that they can restrict access of their app for impersonated user. I googled it, but didn't find many solutions around this area, I tried those, but none of them worked.

Finally I decided to give it a shape by my own, I spent some time on it, did poc and came up with a 100% working solution.

1. Login into Salesforce instance with your credentials.

2. Now open browser console, shortcut key(F12).

3. As you can see in the below image, a cookie is created with "sid" name.


"SID" stands for user's session id cookie which use to uniquely identified Salesforce user.

4. Now "Login as" with different user.

5. See the browser's console again and search for sid, this time you will see 2 cookies, one is "SID" and another is "RSID".


In an ordinary login, the SID cookie stores the user session id which determines the identify of the logged in user. When the administrator logs in as a second user, the SID is overwritten to be of the user the administrator is "impersonating".

The RSID is used to identify that this is an impersonation login and not the actual user. You can further detect the RSID cookie using javascript and pass it to your controller.

When the administrator logs out, the server clears the administrators SID and RSID and sends a new SID to the system and allowing it to be redirected back to the first User.

Popular Salesforce Blogs