Friday, 31 May 2019

Sitecore Azure Search suggestions


One of the more common requests I hear (and quite obvious gap in my opinion) is the support for suggestions when using Azure Search.  Auto-suggestions are supported when using Solr as of 9.0.1 (and SXA supports this in the Search Box rendering parameters) and Azure has both Suggestions and Autocomplete APIs.

I recently had the opportunity to take a crack at this missing feature, which I based off the SXA implementation.

Code is in my GitHub Sitecore-AzureSearch-Suggestions repo.
There are 3 branches:
  • The master branch contains the simplest implementation, however uses Azure Search binaries from NuGet, and has a dependency on SXA.
  • The no-azure-client branch does not use the Azure Search binaries but makes API calls directly like the rest of the Sitecore Azure Search implementation
  • The no-sxa branch contains the implementation with Azure binaries, but no SXA dependency
There is also an Autocomplete implementation in there (partial in some branches).  For a quick overview of the difference see this MS blog post.

Unfortunately the Sitecore Azure Search dlls (Sitecore.ContentSearch.Azure.*) do not seem to be as extensible as the rest of sitecore, as there are numerous internal classes and private methods/properties.

The following classes had to pretty much be copied out as they couldn't be extended :(
  • Sitecore.ContentSearch.Azure.Http.SearchService
  • Sitecore.ContentSearch.Azure.Http.SearchServiceClient properties + GetClient method
  • Sitecore.ContentSearch.Azure.Http.CompositeSearchService
  • Sitecore.ContentSearch.Azure.CloudSearchProviderIndex ConnectionStringName,
  • SearchCloudIndexName properties
  • Sitecore.ContentSearch.Azure.CloudSearchProviderIndexName
  • Sitecore.ContentSearch.Azure.ISwitchSearchIndexInitializable
  • Sitecore.ContentSearch.Azure.Schema.CloudSearchIndexSchema
  • Sitecore.ContentSearch.Azure.Http.MultiStatusResponseDocument
  • All Sitecore.ContentSearch.Azure.Http.Exceptions exceptions
  • Sitecore.ContentSearch.Azure.Exception.CloudSearchCompositeSearchServiceException
  • Sitecore.ContentSearch.Azure.Exception.CloudSearchMissingImplementationException
Hopefully the product team can fix this up for a later version!

Oh and I found a couple of typos while I was in there ;)
  • Sitecore.ContentSearch.Azure.Utils.Retryer.IRertyPolicy
  • /sitecore/media library/Base Themes/SearchTheme/Scripts/component-search-box
    return '<div class="sugesstion-item">' + suggestionText + '</div>';

Thursday, 30 May 2019

A Couple of SIF Enhancements

SIF can be pretty slick (when you've got the prerequisites set up correctly and it works 100%), and the best part about it is that it's quite easy to extend. You can also easily take advantage of some of the functions that the Powershell module exposes.

Adding HTTPS to Sitecore

For some reason although SIF adds SSL bindings for Identity Server and xConnect it doesn't do it for Sitecore.  I like to generate a cert for *.dev.local and *sc, which we can do by tapping into the Invoke-NewSignedCertificateTask exposed by the Powershell module.

There are a couple of ways you can retrieve the Sitecore root cert (which you'll need for signing), but I prefer to be sure I have the correct one (since I have a couple with the same name) and find the thumbprint manually by going into the Certificate Manager (start->run 'certmgr'). Under Trusted Root Certificate Authorities look for DO_NOT_TRUST_SitecoreRootCert. Double click this, go to details, and scroll down to Thumbprint.  You can then insert your thumbprint into the following Powershell script to generate a new cert (in this case a wildcard for *.dev.local with friendly name 'Local Dev Wildcard' and a password for which it prompts you).

$Signer = Get-ChildItem -Path 'Cert:\\LocalMachine\\Root\\YOURTHUMBPRINT'
$SecurePassword = Read-Host -Prompt "Enter password" -AsSecureString 
$dnsName = "*.dev.local",""
Invoke-NewSignedCertificateTask -Signer $Signer -Path 'C:\certificates' -CertStoreLocation 'Cert:\LocalMachine\My' -Name "Local Dev Wildcard" -DnsName $dnsName -IncludePrivateKey -Password $SecurePassword

Don't forget to update your identity server Sitecore.IdentityServer.Host.xml to ensure your sitecore URLs have https!

Updating SIF

Ok so it's obviously pretty straightforward to call manually, but in case you want to incorporate the SSL step into SIF, working backwards you'll need:
  1. sitecore-XP0.json
    • Add a step under CreateBindings with the following:
      "CreateBindingsWithThumbprint": {
        "Description": "Configures the site bindings for the website.",
        "Type": "WebBinding",
        "Params": {
          "SiteName" : "[parameter('SiteName')]",
          "Add": [
              "HostHeader": "[parameter('DNSName')]",
              "Protocol": "https",
              "SSLFlags": 1,
              "Thumbprint": "[variable('Security.Sitecore.CertificateThumbprint')]"
        "Skip": "[not(parameter('SitecoreCert'))]"
    • Add a variable to the Variables section in the middle called Security.Sitecore.CertificateThumbprint with value "[GetCertificateThumbprint(parameter('SitecoreCert'), variable('Security.CertificateStore'))]"
    • Add a parameter to the Parameters section at the top called SitecoreCert (I put it below xConnectCert so it's easy to find)
  2. In XP0-SingleDeveloper.json
    • Add parameter SitecoreXP0:SitecoreCert type String, Reference SitecoreCertificateName to pass the cert name to the XP0 script above
    • Under Includes after SitecoreSolr add:
      "SitecoreCertificates": {
        "Source": ".\\createcert.json"
    • Add parameter SitecoreCertificates:CertificateName type String Reference SitecoreCertificateName to pass the cert name to the createcert script above
    • Add parameter SitecoreCertificateName type String, defaultValue "" to hold the cert name
  3. In XP0-SingleDeveloper.ps1
    • In the $singleDeveloperParams add: SitecoreCertificateName = $SitecoreSiteName to pass the cert name

Sitecore Installation Location

Unfortunately this one is nowhere near is nice :( I have no idea why the location is hardcoded
  1. sitecore-XP0.json
    • set Site.PhysicalPath to "[joinpath(environment('SystemDrive'), parameter('InstallLocation'), parameter('SiteName'))]"
    • Add parameter InstallLocation optionally with "DefaultValue": "[joinpath('inetpub','wwwroot')]"
  2. IdentityServer.json
    • set Site.PhysicalPath to "[joinpath(environment('SystemDrive'), parameter('InstallLocation'), parameter('SiteName'))]"
    • Add parameter InstallLocation optionally with "DefaultValue": "[joinpath('inetpub','wwwroot')]"
  3. xconnect-xp0.json
    • set Site.PhysicalPath to "[joinpath(environment('SystemDrive'), parameter('InstallLocation'), parameter('SiteName'))]"
    • Add parameter InstallLocation optionally with "DefaultValue": "[joinpath('inetpub','wwwroot')]"
  4. XP0-SingleDeveloper.json
    • Add parameter SitecoreXP0:InstallLocation type String with "Reference": "InstallLocation"
    • Add parameter XConnectXP0:InstallLocation type String with "Reference": "InstallLocation"
    • Add parameter IdentityServer:InstallLocation type String with "Reference": "InstallLocation"
    • Add parameter InstallLocation type String with "DefaultValue": "[joinpath('inetpub','wwwroot')]"
  5. XP0-SingleDeveloper.ps1
    • Under $singleDeveloperParams add InstallLocation = $InstallLocation
    • Define your instllation variable above: $InstallLocation = "\sites\mysite"

Friday, 17 May 2019

Azure AD B2C with Sitecore Identity

As with my last post I'm not going to go into detail about how to set up the foundation of a Sitecore Identity plugin, this is just the specifics of Azure AD B2C.

Sample code is on my Sitecore-Identity-AzureADB2C repo

Azure AD B2C

First step is obviously to create an Azure AD B2C instance in Azure.  This will set up an entire new directory that you will need to switch to in order to actually work with the Azure AD B2C tab on the left side of the Portal.

In the Azure AD B2C tab (like in AD or Auth0 and everything else) you'll need to create an Application.  Grab the Application ID (client ID) for setting in the config.  Add the Reply URL: https://your.identity.server/signin-idsrv.

We'll set up a custom user attribute which we'll use to determine whether the user is a Sitecore admin (if you are simply using B2C for an external site you can use a different name or skip this altogether).  Go into User attributes and add a new attribute called SitecoreAdmin of type boolean.

Next up create a User Flow.  I created a "Sign up and sign in v2" but I'd say it will also work with the non-v2 version (I just like using the latest version of everything).  Remember the name of the flow for your config. Inside the flow set the identity providers you want to use - bear in mind for testing it's easiest to set that SitecoreAdmin property on a "Local Account" so include that at the very least.  Under "User Attributes" and "Application Claims" ensure your SitecoreAdmin property is checked so that it is included in the list of claims which Sitecore Identity Server will receive.

Sitecore Identity Server

Grab the code and populate the clientId, tenant, and policy name.
In the Sitecore.Plugin.IdentityProvider.AzureB2C.xml config file note the added transformation:

<ClaimsTransformation3 type="Sitecore.Plugin.IdentityProviders.DefaultClaimsTransformation, Sitecore.Plugin.IdentityProviders">
    <Claim1 type="extension_SitecoreAdmin" value="true" />
    <Claim1 type="" value="true"/>

Our property is exposed as a claim with the name extension_SitecoreAdmin which is mapped as per the documentation (also see the link for the final step of mapping the IsAdministrator property in Sitecore).

Enjoy logging in to Sitecore through Azure AD B2C!

Thursday, 16 May 2019

Auth0 Login with Sitecore Identity

I'm not going to go through and cover all the steps involved in configuring subproviders in Sitecore Identity server by creating a Sitecore Identity plugin as that has been covered numerous times for AD, ADFS, and other external providers.  I'd also recommend this excellent 3-part blog post by Himadri which walks through in a bit more detail how Sitecore Identity works.
I simply thought I'd share the code I developed for a POC recently to get Auth0 working.  Fortunately Auth0 has some great quick-start documentation on Login with .NET Core which translates nicely to the Identity Server format.

See my Sitecore-Identity-Auth0 repo on github for the code.


Log in to Auth0 and create a new application (regular web application).  Give it a name, grab the domain, client id, and secret and put these in the Sitecore.Plugin.IdentityProvider.Auth0.xml file from the code.  Also set the following:
  • Callback URLs:
  • Allowed logout URLs:
Putting the code (with values from above) into Identity Server and logging in should now tell you that you are not authorized to log into Sitecore.  This means it was successful but your user has not been given the necessary Sitecore role to log in to the backend (eg. author / admin)

Additional Claims

Of course simply adding login support isn't generally the end of the story, you might need to ensure your users can log into the Sitecore backend (as authors or admins) or map other properties to the user (eg. interest) when they log in.

Let's create some dummy user properties in Auth0 that we can use to identify a user's role in Sitecore, as well as details we know about them. Create a new user in Auth0 or edit an existing one.
  • Under user_metadata (user-editable data) add: { "interest": "Skiing" }
  • Under app_metadata (not user-editable data) add: { "sitecore_role": "Author", "job_title": "Manager" }

In Auth0 create a new Rule (empty) and paste in the following function:
function (user, context, callback) {
 const namespace = '';
 context.idToken[namespace + 'Interest'] = user.user_metadata.interest;
 context.idToken[namespace + 'SitecoreRole'] = user.app_metadata.sitecore_role;
 context.idToken[namespace + 'JobTitle'] = user.app_metadata.job_title;
 callback(null, user, context);

This maps the user data (that we'll create) to claims in the token which is returned to Sitecore Identity server.  You can make the namespace whatever you like as long as it maps to the same thing in the config we'll add next.

In Sitecore.Plugin.IdentityProvider.Auth0.xml under ClaimsTransformation2 add the following new claims transformations (see Configure claims transformations in the doco for details):
<ClaimsTransformation3 type="Sitecore.Plugin.IdentityProviders.DefaultClaimsTransformation, Sitecore.Plugin.IdentityProviders">
 <Claim1 type="" />
 <Claim1 type="Interest" />
<ClaimsTransformation4 type="Sitecore.Plugin.IdentityProviders.DefaultClaimsTransformation, Sitecore.Plugin.IdentityProviders">
 <Claim1 type="" />
 <Claim1 type="JobTitle" />
<ClaimsTransformation5 type="Sitecore.Plugin.IdentityProviders.DefaultClaimsTransformation, Sitecore.Plugin.IdentityProviders">
 <Claim1 type="" value="Author" />
   <Claim1 type="role" value="sitecore\Author" />
<ClaimsTransformation6 type="Sitecore.Plugin.IdentityProviders.DefaultClaimsTransformation, Sitecore.Plugin.IdentityProviders">
 <Claim1 type="" value="Admin" />
        <Claim1 type="" value="true"/>

You should now be able to log in to the Sitecore back-end as an Author or Admin (or any other role you choose if you customise the code).
To access the Interest or JobTitle properties you can use the following syntax:
  • Sitecore.Context.User.Profile["Interest"]
  • Sitecore.Context.User.Profile.GetCustomProperty("Interest")
Enjoy using Auth0 with Sitecore!