如何在Salesforce Apex或LWC中获取代登录用户的邮箱ID?
获取代登录用户(Manager_A)邮箱的方案
方法一:通过Apex类查询
当使用「以其他用户身份登录」功能时,系统生成的AuthSession记录中,UserId对应被登录的用户(Payee_A),CreatedById则是发起代登录的用户(Manager_A)。基于这个特性,可通过Apex查询获取目标邮箱:
Apex代码示例
public with sharing class ImpersonationUserController { @AuraEnabled(cacheable=true) public static String getImpersonatingUserEmail() { // 查询当前用户的活跃会话 AuthSession currentSession = [ SELECT CreatedById FROM AuthSession WHERE UserId = :UserInfo.getUserId() AND IsCurrent = true LIMIT 1 ]; // 验证是否为代登录场景,查询发起用户的邮箱 if(currentSession != null && currentSession.CreatedById != UserInfo.getUserId()) { User impersonatingUser = [ SELECT Email FROM User WHERE Id = :currentSession.CreatedById LIMIT 1 ]; return impersonatingUser.Email; } // 非代登录场景返回null return null; } }
方法二:在LWC中调用Apex获取
在LWC组件里调用上述Apex方法,即可拿到Manager_A的邮箱:
LWC代码示例
import { LightningElement, wire } from 'lwc'; import getImpersonatingUserEmail from '@salesforce/apex/ImpersonationUserController.getImpersonatingUserEmail'; export default class ImpersonationUserEmail extends LightningElement { impersonatingEmail; error; @wire(getImpersonatingUserEmail) wiredImpersonatingUser({ error, data }) { if (data) { this.impersonatingEmail = data; this.error = undefined; } else if (error) { this.error = error; this.impersonatingEmail = undefined; } } }
注意事项
- 需确保被登录用户(Payee_A)拥有
AuthSession对象的查询权限,以及查看代登录用户(Manager_A)记录的权限 - 非代登录场景下,方法会返回
null,可在LWC中做相应空值处理
内容的提问来源于stack exchange,提问作者R_M_R
相关产品推荐
相关产品推荐

