Skip to main content

Sitecore

Sitecore Federated Authentication Troubleshooting

Istock 948997140 (1)

Introduction

In this blog we will explore Sitecore Federated Authentication Troubleshooting. I used Azure AD B2C as the identity provider in my integration guide you can check here Sitecore federated authentication with azure ad b2c user flow. However the most of these issues are not identity provider specific. When you work on federated authentication there is a good chance that you will fail on your first attempt and potentially face some of the issues described in this blog post. To make your authentication setup hassle-free and smooth here are some of the most common errors and solutions to fix them.

The located assembly’s manifest definition does not match the assembly reference

Since implementing identity providers processor requires adding references to different assemblies like

  • Sitecore.Owin
  • Sitecore.Owin.Authentication
  • Microsoft.Owin
  • Microsoft.IdentityModel.Protocols.OpenIdConnect
  • Microsoft.Owin.Security.OpenIdConnect
  • IdentityModel

you could face an error stating that referenced assemblies version could not be found or not matching referenced version.

The problem:

Because Sitecore distribution comes with its own Identity Server it is already referencing some of these assemblies of certain versions. For example, my local development Sitecore 10.3 instance is referencing IdentityModel.dll version 3.10.10 but the latest NuGet package is version 6.2 at the time of writing this blog post. Installing the latest will cause this error to appear.

The solution:

You need to check specific assembly version on your running Sitecore instance and make sure you add the same version as a reference in your project. To check which version your Sitecore is referencing you can open the Web.config and find your problematic assembly by name. To check assembly version of the actual file in your running instance you can use this powershell command. Navigate to bin folder and run this command:

Get-Item .\IdentityModel.dll | Select-Object Name,@{n='FileVersion';e={$_.VersionInfo.FileVersion}},@{n='AssemblyVersion';e={[Reflection.AssemblyName]::GetAssemblyName($_.FullName).Version}}

NOTE: If you are using Docker containers you can first shell into your running container and check assembly versions there using the same PS command.

Configuration and Sitecore Topology

Since we are using federated authentication to authenticate users for Content Delivery instance, for environments where you have XP Scaled topology, separate CM and CD instances, you should enable the identity configuration only for ContentDelivery role. In cases where your topology is XP single you will have to enable identity configuration for ContentManagement role as well.

The problem:

Enabling federated authentication configuration for ContentManagement could cause redirecting your content authors to Azure AD B2C login page instead of Sitecore’s identity server login page. Sitecore documentation recommends using /sitecore and /sitecore/admin URLs to access Sitecore. In my case this resolves to https://aip.sc/sitecore and https://aip.sc/sitecore/admin and both options redirect to Azure AD B2C.

The solution:

To avoid this, make sure to use environment specific config files to prevent identity configuration patch being applied on upper environment’s CM instances. If you still need to have identity config enabled for ContentManagement role, the safest way you can access Sitecore is to use https://aip.sc/sitecore/login URL. Using old login page should also work for you https://aip.sc/sitecore/login?fbc=1

If you want to find more information about authentication changes which affect Sitecore login page, you can refer to this link: https://doc.sitecore.com/xp/en/developers/103/sitecore-experience-manager/understanding-sitecore-authentication-behavior-changes.html

Redirecting back to http instead of https

The problem:

When you start authentication process and you successfully authenticate, you are redirected back on the page you initially started from. If you don’t see your claims, you didn’t receive any error in the process and it looks like nothing actually happened you should check if you got redirected back on http instead of https. This can happen if you are running behind a proxy such as traefik in docker containers setup.

The solution:

To fix this issue, you should implement the extension method needed for operating a website on a HTTP connection behind a proxy which handles SSL hand-off. Such a proxy adds the X-Forwarded-Proto header to indicate the nature of the client’s connection. This is an example of AppBuilderExtension class

using Owin;
using System;

namespace AuthIntegrationPlayground.Identity.Extensions.Owin
{    
    public static class AppBuilderExtensions
    {
        private const string ForwardedProtoHeaderAdded = "ForwardedProtoHeaderAdded";
        
        public static IAppBuilder UseForwardedProtoHeader(this IAppBuilder app)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            // No need to add more than one instance of this middleware to the pipeline.
            if (app.Properties.ContainsKey(ForwardedProtoHeaderAdded))
            {
                return app;
            }

            app.Properties[ForwardedProtoHeaderAdded] = true;

            app.Use(async (context, next) =>
            {
                var request = context.Request;

                if (request.Scheme != Uri.UriSchemeHttps && string.Equals(request.Headers["X-Forwarded-Proto"], Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase))
                {
                    context.Request.Scheme = "https";
                }

                await next.Invoke();
            });

            return app;
        }
    }
}

And this is how we can use it inside AzureADB2CIdentityProvider.cs

protected override void ProcessCore(IdentityProvidersArgs args)
{
    try
    {        
        //OpenIdConnectAuthenticationOptions
        
        args.App.UseForwardedProtoHeader();//<--- App builder extension
        args.App.UseOpenIdConnectAuthentication(options);
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

IDX21323: RequireNonce is ‘[PII is hidden]’ Error

This is one of the most annoying errors which can turn your Sitecore federated authentication troubleshooting into a endless loop of searching for a solution and trying it to see if it works.

The problem:

Root cause of this error is a well known issue in asp.net Katana implementation. More about this issue can be found here https://github.com/aspnet/AspNetKatana/wiki/System.Web-response-cookie-integration-issues. In essence this error will show when OpenIdConnect could not validate nonce value due to a missing nonce cookie. However this error can be misleading and can appear for many different reasons:

  • Not using Sitecore’s GetSignInUrlInfo pipeline to generate the valid sign in URL
  • Website domain and the redirectURI domain are different and Sitecore does not have access to the nonce cookie after successful authentication
  • Nonce cookie is returning from the server but the browser blocks it. This could happen if you’re not using https. It can even be due to time difference(time not set properly) browser can mark cookie as expired
  • Clearing Cookies between the sign in URL generation and redirect back from the external provider

Some less obvious issues that could produce this error:

  • Disabled xDB and/or xDB.Tracking in some cases
  • Token endpoint URL inside OnCodeRecieved is not resolving properly (misconfiguration)

The solution:

From development standpoint the easiest solution to fix this error is adding CookieManager = new SystemWebCookieManager() inside OpenIdConnectAuthenticationOptions.

If this doesn’t work and you are unable to determine what is causing the issue you can try the following:

  • Probably the best way for Sitecore federated authentication troubleshooting is just using Visual Studio debugger. Connect your VS debugger to the running instance and put breakpoints inside notification methods and your AuthController. For this to work make sure you publish as debug not release. Step by step go thru authentication starting from generating signin URL to receiving claims and showing them on the page. Pay attention to endpoint URLs and OpenIdConnectAuthenticationOptions properties
  • Try finding more information by looking at Owin.log or your system’s Event Viewer
  • If you implemented any custom logic inside notification methods(calling external services or modifying authentication request) try commenting it out

Generic ‘An Error Occurred’ error message

In some cases, usually after extending or changing your code, you could face the exception message which will just say ‘An Error Occurred’. In this case your best bet is to revisit complete authentication setup and make sure all integral parts are there. Be aware of any code changes which could be affecting the authentication process. If you suspect this error is coming from Azure AD B2C, having Application Insights can help you determine the actual cause of this error.

Summary

In this blog we went over some of the most common issues you can face during Sitecore and Azure AD B2C integration. Since this integration is complex in its nature there are many factors that can affect the outcome. Assembly versions, configurations on Sitecore and Azure AD B2C side, custom code or external dependencies could cause authentication to fail. The key note for successful Sitecore federated authentication troubleshooting in general is to think in a way which will lead you towards finding the root cause and therefore being able to fix it. Often you will find yourself searching for an answer on internet without even knowing what is the error.

Final word of advice

Here are a few advices for making it easier for you when working on federated authentication.

  • Avoid implementing it all at once – It is not advisable to do complete implementation with all the claim transformations, custom user builder, pulling user data from external APIs, extending xConnect contact model etc. before being able to authenticate with a minimum required for authentication. It is not necessarily a bad thing but if you start facing errors during authentication you could have a hard time finding out what is causing the authentication to fail. Instead, try implementing just a minimum which works without issues and then move to extending it according to your needs.
  • Avoid using different guides as reference – If you are using different guides as a reference and referencing different parts of those guides you could end up having the unusable solution and ultimately rewriting complete implementation from start. The reason is there are different guides for different Sitecore versions and some outdated guides for Azure AD B2C. You should always refer to Sitecore’s and Microsoft’s documentation since it is up to date, as well following guides which are specific for your Sitecore version and project setup.
  • Keep in mind the final result – After a few iterations you will reach desired state for your authentication process. But before you start working on it you should plan in advance. It is a good thing to have everything documented in one place. For complex scenarios you should always have diagrams supporting your solution. You should know the use cases for your claims and access tokens(if any) so you can get things done in a way which will support it at the end. With this documented knowledge you will see the long term benefit since you can use it as a future reference.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Slobodan Topic

Hello! I'm Slobodan, a seasoned developer with six years in .NET. Transitioning into Sitecore, I've become passionate about crafting seamless digital experiences. In my posts, I demystify complex topics like Sitecore user identity, federated authentication and integration with external identity providers.

More from this Author

Categories
Follow Us
TwitterLinkedinFacebookYoutubeInstagram