How to get IP Address of Community User – Guest and Logged in Customer User

DESCRIPTION

Tracing IP address of community is utmost requirement to achieve different goals like geo based technical support, spam protection and other security things.

There are bunch of forum discussions related to this:

https://developer.salesforce.com/forums/?id=9062I000000g56rQAA

https://salesforce.stackexchange.com/questions/145145/how-to-get-ip-address-of-current-user-in-lightning-component

https://salesforce.stackexchange.com/questions/246085/how-to-get-the-public-ip-address-of-current-user-in-lightning-component-hosted-o/246087

APPROACHES

In order to solve this, simple approach is to get the IP address and store in any custom field of Case or any community related object. All possible approaches are explained further:

Logged in User IP Address

Getting IP Address for logged in user is relatively simple as Salesforce stores this information in two standard objects: AuthSession, LoginGeo.

While page (Lightning component/LWC) is loading, we can make server call to get these information and save it in database in subsequent events. We can use following code snippet

AuthSession as =  [SELECT LoginGeoId , LoginType, SourceIp FROM AuthSession WHERE UsersId=: UserInfo.getSessionId() AND IsCurrent = true LIMIT 1];
LoginGeo lg = [SELECT City, Country, PostalCode, Subdivision,  Latitude, Longitude FROM LoginGeo WHERE Id = as.LoginGeoId];

Alternatively, you can use Auth.SessionManagement Class as well as below:

Auth.SessionManagement.getCurrentSession().get('SourceIp');

getCurrentSession() returns all valuable information in key pair as below

{
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
}

Guest User IP Address

This one is tricky as there is no standard way to get it. The above given method either returns wrong ip address (Salesforce server address) or throws error stating it’s not possible in the context of guest user.

There are two workarounds to achieve this.

  • Using VF page as below
    • We can embed this VF page as Iframe in any lightning component and pass the ip address to parent lightning component using ‘postMessage’ approach.
<apex:page showHeader="false" sidebar="false" controller="IPAddressController" action="{!getUserIPAddress}">
 <script>
    setTimeout(function(){
        var message = '{!ip}';
        parent.postMessage(message, window.top.location.origin);         
     }, 3000);
 </script>
 <apex:form >
     {!ip}
 </apex:form>
</apex:page>

public class IPAddressController{
    public string ip {get;set;}
    public pageReference getUserIPAddress() {
        
        // True-Client-IP has the value when the request is coming via the caching integration.
        ip = ApexPages.currentPage().getHeaders().get('True-Client-IP');
        
        // X-Salesforce-SIP has the value when no caching integration or via secure URL.
        if (ip == '' || ip == null) {
            ip = ApexPages.currentPage().getHeaders().get('X-Salesforce-SIP');
        } 
        
        // get IP address when no caching (sandbox, dev, secure urls)        
        if (ip == '' || ip == null) {
            ip = ApexPages.currentPage().getHeaders().get('X-Forwarded-For');
        }
        
        //get IP address from standard header if proxy in use
        //ip = ApexPages.currentPage().getHeaders().get('True-Client-IP');  
        return null;
        
    }
}
  • Using any geolocation api like google, apify or anyone elsePAID
    • We can make http call from client side javascript and get IP address and other geo detail.
    • However, this approach will cost us and need to buy the api
       const Http = new XMLHttpRequest();
        const url='https://api.ipify.org/';
        Http.open("GET", url);
        Http.send();
        Http.onreadystatechange=(e)=>{
            console.log(Http.responseText); // This prints Ip address
            component.set("v.ipAddress", Http.responseText);
        }

Contact us for any help here: ayub.salsforce@gmail.com

4 thoughts on “How to get IP Address of Community User – Guest and Logged in Customer User”

Comments are closed.