“Log in to Community as User” – How to detect in Apex?

Introduction “Log in to Community as User”

“Log in to Community as User” is a feature provided by Salesforce, which allows users with “Manage External Users” permission login to the community as a selected account’s contact (user).
It can be a potential cause of problems because in some cases we want to hide some sensitive data before internal users. Below I described a logic that helps you to detect if an internal user is logged to the community on behalf of community user.

If we want to see “Log in to …” button, we must fulfill a few points:

– Ensure that Communities are enabled in your org.
– Ensure that your profile has Manage External Users’ permission.
– Ensure that the contact is associated with an account.

log in to community
log in to community

After clicking this button you should be able to log in to a community in contact (user) context, has whole access to the user’s system and do action on his behalf.

The question is “How we can detect that current user is log in on behalf of contact?”

Apex code

We can use the standard Apex method Auth.SessionManagement.getCurrentSession(), which provide some session information:

{
  SessionId=0Ak###############, 
  UserType=Standard, 
  ParentId=0Ak###############, 
  NumSecondsValid=7200, 
  LoginType=SAML Idp Initiated SSO, 
  LoginDomain=null,
  LoginHistoryId=0Ya###############,
  Username=user@domain.com, 
  CreatedDate=Wed Jul 30 19:09:29 GMT 2014, 
  SessionType=Visualforce, 
  LastModifiedDate=Wed Jul 30 19:09:16 GMT 2014, 
  LogoutUrl=https://google.com, 
  SessionSecurityLevel=STANDARD,
  UsersId=005###############, 
  SourceIp=1.1.1.1
}

We can easily check that someone else is logged in to a community as a current user checking UserType, SourceIp and LoginType.

    public Boolean isAnotherUserLoginOnBehalf() {
        Map<String, String> session = Auth.SessionManagement.getCurrentSession();
        return session.get('UserType') == 'Standard' &&
               session.get('SourceIp') == '::' && 
               session.get('LoginType') == null;
    }

Resources

Was it helpful? Check out our other great articles here.

4.9 9 votes
Article Rating
Subscribe
Notify of
guest
2 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
trackback

[…] "Log in to Community as User" – How to detect in Apex … […]

Stephen Lombard
Stephen Lombard
1 year ago

I used this code a few months back and it worked. Yesterday I noticed SF is returning LoginType=Unknown in a visualforce session. I’m wondering if this is a stable approach.

Close Menu
2
0
Would love your thoughts, please comment.x
()
x