Retrieve IP Address for the Guest Users in Lightning Community

Recently, we received a requirement where we needed to track the IP address of the guest users on the Salesforce Lightning Community.

One of the ways to get the IP address of the current user in Apex is using the following method:

But this method works only for logged in users and gives an error for the guest users. We tried getting the IP address from the cookies also, but it's not a good idea because it is really not necessary that for guest users, you will get the IP address in the cookies always.

At last, we came up with the following workaround to solve this riddle:

1) Create the following apex controller (ViewIPAddressController):
 public class ViewIPAddressController{
    public String ipAddress{get; set;}

    public ViewIPAddressController(){
        //this will work if no caching is in place or
        //user is logged in via secure URL
        ipAddress = ApexPages.currentPage().getHeaders().
        //this logic will execute if proxy is in use
           ipAddress = ApexPages.currentPage().getHeaders().

2) Now, create the following Visualforce page (ViewIPAddress):
 <apex:page controller="ViewIPAddressController" showHeader="false">

3) Now, use below piece of code wherever you want to get the IP Address of the guest user, it can be any apex class or @AuraEnabled method in the Lightning Component's Controller:
String ipAddress = (new PageReference('/apex/ViewIPAddress')).
                   substringBetween('<ipAddress>', '</ipAddress>');

So, using this small workaround, we can easily implement this tedious requirement. Hope this is helpful.

Happy Coding!!


Popular posts from SFDC Drona

Email Alert to Parent object's email field without apex

Visualforce header and sidebar do not appear on IE11 (or lower version of IE) even when enabled