Sitecore Geo IP Services (SC 10.2) Updated

Many businesses require to implements GEO IP Services. Business Rules differ between locations. As Developers, Sitecore makes our lives easier by providing a Service that we can use to obtain the location of the website’s visitor.

The IP Geolocation provides information like country, state, city, and every visitor’s registered company name as well. Based on geodata, we can build modules that interact with our visitors and provide accurate information depending on where they are.

Installation and Configuration

Here you will find the official link to activate and set up the Sitecore IP Geolocation: Set up Sitecore IP Geolocation

In your Siecore Solution ensure you add the following Nuget Packages:

  • Sitecore.Kernel
  • Sitecore.Analytics

Solution

Sometimes when you work with lower environments or your local environment Geo IP is not available. I developed the following simple class to get the visitor’s country and city. We can add the next file to setup a city and country code when Sitecore IP Geolocation is not available for your local. I used Sitecore 10.2.


<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:set="http://www.sitecore.net/xmlconfig/set/" xmlns:env="http://www.sitecore.net/xmlconfig/env/">
  <sitecore>
    <settings env:require="Local">
      <setting name="Dev.IPGeolocation.IsDevMode" value="true"/>
      <setting name="Dev.IPGeolocation.City" value="Boston"/>
      <setting name="Dev.IPGeolocation.CountryCode" value="US"/>
    </settings>
  </sitecore>
</configuration>

The next class contains a method GetUserGeolocation to get user location information.

Noticed IGeoIPManager is injected on the constructor class.

 public class GeolocationService : IGeolocationService
    {
        private readonly IGeoIpManager _geoIpManager;

        public GeolocationService(IGeoIpManager geoIpManager)
        {
            _geoIpManager = geoIpManager;
        }
        /// <summary>
        /// Get User IP form Request Context.
        /// </summary>
        /// <returns>(string) IP Address</returns>
        private static string GetUserIP()
        {
            var ip = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null
                      && HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != "")
                ? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]
                : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            if (ip.Contains(","))
                ip = ip.Split(',').First().Trim();

            return ip.Trim();
        }

        /// <summary>
        ///   Fetch country from Sitecore IP Geolocation Service check 
        ///   setup at https://doc.sitecore.com/developers/93/sitecore-experience-manager/en/set-up-sitecore-ip-geolocation.html
        /// </summary>
        /// <returns></returns>
        public GeoData GetUserGeolocation()
        {
            GeoData geoData;
            bool IsDevEnviroment = Settings.GetBoolSetting("Dev.IPGeolocation.IsDevMode", false);
            if (!IsDevEnviroment)
            {
                try
                {
                    var result = _geoIpManager.GetGeoIpData(GetUserIP());
                    if (result.Status == GeoIpFetchDataStatus.Fetched &&
                        result.WhoIsInformation != null)
                    {
                        geoData = new GeoData()
                        {
                            City = result.WhoIsInformation.City,
                            CountryCode = result.WhoIsInformation.Country
                        };
                    }
                    else
                    {
                        throw new Exception("GeoIP whoIsInformation is null");
                    }
                }
                catch (Exception e)
                {
                    Log.Error("Error Getting IPAddress", e, typeof(GeolocationService));
                    if (Tracker.Current != null && Tracker.Current.Interaction != null && Tracker.Current.Interaction.GeoData != null)
                    {
                        geoData = new GeoData()
                        {
                            City = Tracker.Current.Interaction?.GeoData?.City,
                            CountryCode = Tracker.Current.Interaction?.GeoData?.Country
                        };

                    }
                    else
                    {
                        Log.Error("IPGeolocation: There is an issue with IP Geolocation Service", typeof(GeolocationService));
                        geoData = new GeoData()
                        {
                            City = null,
                            CountryCode = Settings.GetSetting("LocationEngine.IPGeolocation.CountryCode")
                        };
                    }
                }

            }
            else
            {
                Log.Info("IPGeolocation: Dev Mode is enabled", typeof(GeolocationService));
                geoData = new GeoData()
                {
                    City = Settings.GetSetting("Dev.IPGeolocation.City"),
                    CountryCode = Settings.GetSetting("Dev.IPGeolocation.CountryCode")
                };
            }
            Log.Info($"IPGeolocation: Country Code is {geoData.CountryCode}", typeof(GeolocationService));
            return geoData;
        }
    }

Finally, GeoData is a model class that contains the location information.


 public class GeoData
    {
        public string CountryCode { get; set; }
        public string City { get; set; }
    }

I hope this information will be usefully when you work with Sitecore Geo IP Services.

Read more

Sitecore Forms: ReCaptcha Enterprise Support

Sitecore is a powerful DXP it is desiged for enterprise-level websites. As Marketers you would need to set up your forms and Sitecore provides a solution out-of-the-box to easily create your own forms by drag and drop your form controls like: Text, Buttons, Inputs and customize submit actions. However, your site is vulerable to bot attacks and some companies prefers to use Google’s reCaptcha to prevent bot traffict to their websites.

I’ve been working on a Sitecore forms module, which support the ReCaptcha Enterprise version within Sitecore Forms. If you want to contribute in the module development please refer the following Github Repo:

https://github.com/RobertoArmas/Sitecore-Forms-ReCaptcha

Installation

To make it easily to install you need to add a Nuget Package in your Webiste project.

Install-Package SitecoreModules.Foundation.Forms

Configuration

To setup the module it is required to add Google ReCaptcha Keys Refer to this google docs: https://cloud.google.com/recaptcha-enterprise/docs/keys

Once you installed the nuget package. The installation will add a config file: \Website\App_Config\Include\Foundation\SitecoreModules.Foundation.Forms.ReCaptchaEnterprise.nonprod.config.example

You need to clone it and change it accordingly your environment.

SettingValue
Foundation.Forms.ReCaptchaEnterprise.Api.Urlhttps://www.google.com/recaptcha/enterprise.js?render={0}
Foundation.Forms.ReCaptchaEnterprise.Api.SiteVerifyhttps://recaptchaenterprise.googleapis.com/v1/projects/[PROJECT-ID]/assessments?key={0}
Foundation.Forms.ReCaptchaEnterprise.PublicKeyV3[Public – V3]
Foundation.Forms.ReCaptchaEnterprise.PublicKeyV2[Public – V2]
Foundation.Forms.ReCaptchaEnterprise.ApiKey[Api Key] – This is used for Server Side Validation
Foundation.Forms.ReCaptchaEnterprise.ScoreDefault to 0.5.

Finally, you need to ensure that forms.recaptcha.js is added on standard values to load the js functionality that is required to work, as the following screenshot.

Usage

This module is easy to use. All you need to do is Drag and Drop the control named: “ReCaptcha Enterprise” which is located under Security section.

Then you can configure the module by click on it, then select the mode, it could be:

  • Invisible: Provides a better user experience, reCaptcha v3 is invisible for webiste visitors.
  • Checkbox: Use a challenge if Google detects a bot behaviour.

Finally, save your form. I hope you find this modue useful on your projects.

Read more