IDX21323 OpenIdConnectProtocolValidationContext.Nonce was null, OpenIdConnectProtocolValidatedIdToken.Paylocad.Nonce was not null

▼魔方 西西 提交于 2019-12-01 07:28:37

问题


I'm attempting to authenticate for Azure AD and Graph for an Intranet (Based off Orchard CMS), this functions as expected on my local machine, however, when accessing what will be the production site (already set up with ssl on our internal dns), I get the above error at times, it's relatively inconsistent, others in my department while accessing usually get this error.

My Authentication Controller is as follows:

public void LogOn()
    {
        if (!Request.IsAuthenticated)
        {

            // Signal OWIN to send an authorization request to Azure.
            HttpContext.GetOwinContext().Authentication.Challenge(
              new AuthenticationProperties { RedirectUri = "/" },
              OpenIdConnectAuthenticationDefaults.AuthenticationType);
        }
    }

    public void LogOff()
    {
        if (Request.IsAuthenticated)
        {
            ClaimsPrincipal _currentUser = (System.Web.HttpContext.Current.User as ClaimsPrincipal);

            // Get the user's token cache and clear it.
            string userObjectId = _currentUser.Claims.First(x => x.Type.Equals(ClaimTypes.NameIdentifier)).Value;

            SessionTokenCache tokenCache = new SessionTokenCache(userObjectId, HttpContext);
            HttpContext.GetOwinContext().Authentication.SignOut(OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType);
        }

        SDKHelper.SignOutClient();

        HttpContext.GetOwinContext().Authentication.SignOut(
          OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType);
    }

My openid options are configured as follows:

AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;

        var openIdOptions = new OpenIdConnectAuthenticationOptions
        {
            ClientId = Settings.ClientId,
            Authority = "https://login.microsoftonline.com/common/v2.0",
            PostLogoutRedirectUri = Settings.LogoutRedirectUri,
            RedirectUri = Settings.LogoutRedirectUri,
            Scope = "openid email profile offline_access " + Settings.Scopes,
            TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = false,
            },
            Notifications = new OpenIdConnectAuthenticationNotifications
            {
                AuthorizationCodeReceived = async (context) =>
                {
                    var claim = ClaimsPrincipal.Current;
                    var code = context.Code;                        

                    string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;


                    TokenCache userTokenCache = new SessionTokenCache(signedInUserID,
                        context.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase).GetMsalCacheInstance();
                    ConfidentialClientApplication cca = new ConfidentialClientApplication(
                        Settings.ClientId,
                        Settings.LogoutRedirectUri,
                        new ClientCredential(Settings.AppKey),
                        userTokenCache,
                        null);


                    AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, Settings.SplitScopes.ToArray());
                },
                AuthenticationFailed = (context) =>
                {
                    context.HandleResponse();
                    context.Response.Redirect("/Error?message=" + context.Exception.Message);
                    return Task.FromResult(0);
                }
            }
            };

        var cookieOptions = new CookieAuthenticationOptions();
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseCookieAuthentication(cookieOptions);

        app.UseOpenIdConnectAuthentication(openIdOptions);

The url for redirection is kept consistent both at apps.dev.microsoft.com and in our localized web config.


回答1:


Check the URL mentioned in the AD App Registrations --> Settings --> Reply URL's. if for example that url is https://localhost:44348/

Go to MVC Project --> Properties (Right Click and Properties) --> Web Section --> Start URL and Project URL should also be https://localhost:44348/

This has resolved the issue for me. other option is to dynamically set the Redirect URL after AD authentication in Startup.Auth




回答2:


How to solve IDX21323

The problem is solved with this lines of codes, the reason of the error was that ASP.NET don't has the sessión info created yet. The function "authFailed.OwinContext.Authentication.Challenge()" fill the header with the info that needs for the authentication.


        app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions()
    {
        Notifications = new OpenIdConnectAuthenticationNotifications()
        {
            AuthenticationFailed = AuthenticationFailedNotification<OpenIdConnect.OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> authFailed =>
            {
                if (authFailed.Exception.Message.Contains("IDX21323"))
                {
                    authFailed.HandleResponse();
                    authFailed.OwinContext.Authentication.Challenge();
                }

                await Task.FromResult(true);
            }
        }
    });



回答3:


With it being inconsistent, it makes me believe the error you are seeing is caused by what people call "Katana bug #197".

Luckily, there is a workaround with a nuget package called Kentor.OwinCookieSaver.

After installing the nuget package add app.UseKentorOwinCookieSaver(); before app.UseCookieAuthentication(cookieOptions);.

For more info, checkout the Kentor.OwinCookieSaver repo on GitHub.




回答4:


I've got the same error in production environment while locally it worked for all development team. I've tried Kentor.OwinCookieSaver solution suggested by Michael Flanagan but it did not help. After digging a little bit I discovered that authentication itself completed successfully and OwinContext contains user identity and claims, but AuthenticationFailed event handler is raised with IDX21323 exception. So I decided to use the following workaround - I updated AuthenticationFailed event handler:

// skip IDX21323 exception
if (context.Exception.Message.Contains("IDX21323"))
{
   context.SkipToNextMiddleware();
} else {
   context.HandleResponse();
   context.Response.Redirect("/Error?message=" + context.Exception.Message);
}
return Task.FromResult(0);

This way system will not throw IDX21323 exception but continues auth process and allows users to login and use the system.

I know this not a solution, but at least users can now login until I find a better way to solve this issue.




回答5:


My start and project URL's were different than the Redirect URI in Azure. I made all these match and no longer get IDX2132 error.



来源:https://stackoverflow.com/questions/49944071/idx21323-openidconnectprotocolvalidationcontext-nonce-was-null-openidconnectpro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!