Search code examples
salesforceapexsalesforce-lightningsoqllwc

How can I get the email Id of the user who 'Logged in as' another user in Salesforce Apex or LWC


Let's say manager_a has permission to view the account of payee_a, so manager_a logs in to payee_a, inside I have my LWC app, I can able to get the payee_a's email id using

import userEmailFIELD from "@salesforce/schema/User.Email";

But I want the manager_a email id also in my app, is there way I can get the logged in as user email id either in LWC or in Apex class

I tried the authSession object in salesforce, but it's giving me all the emailId in that session, but I want the specific user who impersonating as another user


Solution

  • Not reliably.

    You can use https://salesforce.stackexchange.com/a/222302/799 to detect if there's something fishy going on. And then try querying SetupAuditTrail table, this could be a good start

    select Id, Action, CreatedBy.Email, DelegateUser, CreatedDate, Display
    FROM SetupAuditTrail
    WHERE Action IN ('suOrgAdminLogin', 'suOrgAdminLogout')
    

    But I expect it to fail if you're logged in as non-admin and don't have access to Trail (for example no "Customize Application" permission). So it might have to be something you check after the fact, maybe nightly job that reads the Trail, checks times and flags some records as suspicious?

    If you have event monitoring addon (standalone or as part of Salesforce Shield) maybe there's an event you could listen to generated during Login As