Sitecore Federated Authentication and that annoying error IDX21323: RequireNonce is '[PII is hidden]'
Tags: sitecore, owin, sso, webdev
Published: 2023-05-02 18:17:55

Have you ever experienced an error that keeps appearing under different circumstances and seems to be caused by random reasons? You can fix it once or twice but it comes back in a couple of days or in another environment or for another user. This was the error IDX21323 for me, it was so annoying that after a few cases I started saying "No, not you again!" 😅

---

I worked with Federated Authentication in different versions of Sitecore and integrated it with multiple identity platforms such as Okta, Auth0 and Azure AD B2C. It is a good foundational layer that provides a lot of core functionality out-of-the-box, but there is still plenty of room for mistakes and learnings. In this article I want to share some of these learnings, specifically about the error **IDX21323: RequireNonce is '[PII is hidden]'**.


The main symptom of it is the fact that Sitecore does not authenticate the user correctly after successful redirect back from the identity provider login page. Instead of the configured `redirectURL`, it sends user to the `/error` page with the following message in the URL query string:


> IDX21323: RequireNonce is '[PII is hidden]'. OpenIdConnectProtocolValidationContext.Nonce was null, OpenIdConnectProtocol.ValidatedIdToken.Payload.Nonce was not null. The nonce cannot be validated. If you don't need to check the nonce, set OpenIdConnectProtocolValidator.RequireNonce to 'false'. Note if 'nonce' is found it will be evaluated.

The message itself is not very clear but we can see more details in the `Owin.log` file:

```
26672 08:37:29 WARN  Microsoft.Owin.Security.OpenIdConnect.OpenIdConnectAuthenticationMiddleware - The nonce cookie was not found.
26672 08:37:29 ERROR Microsoft.Owin.Security.OpenIdConnect.OpenIdConnectAuthenticationMiddleware - Exception occurred while processing message: 
Exception: Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectProtocolInvalidNonceException
Message: IDX21323: RequireNonce is '[PII is hidden]'. OpenIdConnectProtocolValidationContext.Nonce was null, OpenIdConnectProtocol.ValidatedIdToken.Payload.Nonce was not null. The nonce cannot be validated. If you don't need to check the nonce, set OpenIdConnectProtocolValidator.RequireNonce to 'false'. Note if a 'nonce' is found it will be evaluated.
Source: Microsoft.IdentityModel.Protocols.OpenIdConnect
   at Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectProtocolValidator.ValidateNonce(OpenIdConnectProtocolValidationContext validationContext) in C:\agent2\_work\56\s\src\Microsoft.IdentityModel.Protocols.OpenIdConnect\OpenIdConnectProtocolValidator.cs:line 639
   at Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectProtocolValidator.ValidateAuthenticationResponse(OpenIdConnectProtocolValidationContext validationContext) in C:\agent2\_work\56\s\src\Microsoft.IdentityModel.Protocols.OpenIdConnect\OpenIdConnectProtocolValidator.cs:line 264
   at Microsoft.Owin.Security.OpenIdConnect.OpenIdConnectAuthenticationHandler.<AuthenticateCoreAsync>d__11.MoveNext()
```

Ultimately this error means that the Owin middleware was not able to read the nonce cookie. In fact, `OpenIdConnectProtocolValidator` can return many other error codes but I'll focus just on one of them today. So why can this error appear?

## Federated Authentication process

To answer this question, we need to understand how Sitecore Federated Authentication works and what it does behind the scenes.
Here is how the happy path should look like: 

![Sitecore Federated Authentication process steps](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2figpvrkshdrbejw0fko.png)

**Step 1.** Browser requests a page that contains a login link.
**Step 2.** Sitecore finds the `IdentityProvider` registered for the specified website name and generates login URL using the pipeline `GetSignInUrlInfo`.
**Step 3.** User clicks the login link and browser sends a POST request to the generated login URL.
The URL should start from `/identity/externallogin?...`
**Step 4.** The processor `HandleLoginLink` performs the following logic:
- ensures that the request method is POST
- includes `RedirectUri` parameter in the Authentication properties
- calls OWIN  `AuthenticationManager.Challenge()` method passing the correct authentication type
Then OWIN generates nonce, saves it in a cookie and redirects to the identity provider passing the nonce in the message.

**Step 5.** Browser redirects user to the Identity Provider sign in page.
**Step 6.** IDP authenticates the user and returns a JWT token.
**Step 7.** Browser redirects back to Sitecore application with JWT token.
**Step 8.** OWIN validates that nonce returned in the JWT token is valid and matches the original nonce cookie.
Sitecore `IdentityProviderProcessor` validates the token, authenticates the user and redirects to the specified `RedirectUri`.

If something goes wrong at any of these steps, the error IDX21323 can appear. There are some common reasons that can cause it:
- Sitecore pipeline `GetSignInUrlInfo` was not used for generating the sign in URL.
- Original domain of the website and the configured redirect URL domain are different, therefore Sitecore does not have access to the nonce cookie after redirect back from the identity provider.
- Cookies or session was cleared between the sign in URL generation and redirect back from the external provider.
- Nonce cookie is returned by the server but the browser blocks it.
- ASP.NET Session ID cookie is not created.

For example, the last time I saw this error it was intermittent and happened only on one machine and we could not reproduce it anywhere else. It turned out that the problem was caused by the disabled `xDB.Enabled` and `xDB.Tracking.Enabled` settings. If a request to the login page was made in a new incognito browser window, there was no ASP.NET Session ID cookie created before the redirect was made to the identity provider, therefore Sitecore could not validate that the response from the identity provider was made from the same user session. 

> The root cause of this behaviour is a bug in Microsoft's Owin implementation for System.Web - sometimes cookies are not saved correctly due to a conflict between Owin and System.Web libraries, as a result ASP.NET_SessionId and Owin-related cookies are not saved and it breaks authentication process. You can read more about this bug and possible workarounds on [this page](https://github.com/aspnet/AspNetKatana/wiki/System.Web-response-cookie-integration-issues).

## Troubleshooting steps

If you faced this error, the following steps can help to troubleshoot it:
1. Look at requests on the browser Network tab.
It can be an IIS redirect that breaks the POST request and the problem is not even in the nonce cookie!
2. Check that the cookies are generated and saved correctly - both ASP.NET Session ID and nonce cookie.
3. If the website redirects back to the /error page, check the error message in query string.
4. Review Sitecore log and Owin.log for any relevant error messages.

Bonus tip:
If you have just started integration and don't have any components that display the logged in user details yet, create a simple test rendering that will output all information required for debugging.