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.

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
- https://help.salesforce.com/articleView?id=000338375&type=1&mode=1
- https://dreamevent.secure.force.com/articleView?id=networks_create_external_users.htm&type=5
- https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_class_Auth_SessionManagement.htm
Was it helpful? Check out our other great articles here.
[…] "Log in to Community as User" – How to detect in Apex … […]
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.