【问题标题】:IDX21323 OpenIdConnectProtocolValidationContext.Nonce was null, OpenIdConnectProtocolValidatedIdToken.Payload.Nonce was not nullIDX21323 OpenIdConnectProtocolValidationContext.Nonce 为空,OpenIdConnectProtocolValidatedIdToken.Payload.Nonce 不为空
【发布时间】:2018-04-20 14:33:06
【问题描述】:

我正在尝试验证 Azure AD 和 Graph 的 Intranet(基于 Orchard CMS),这在我的本地计算机上按预期运行,但是,当访问将成为生产站点时(已经设置了 ssl我们内部的dns),有时会出现上述错误,相对不一致,我部门的其他人在访问时通常会出现此错误。

我的认证控制器如下:

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);
    }

我的openid选项配置如下:

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);

在 apps.dev.microsoft.com 和我们本地化的网络配置中,重定向的 url 保持一致。

【问题讨论】:

    标签: c# azure-active-directory microsoft-graph-api orchardcms


    【解决方案1】:

    就我而言,这是一个非常奇怪的问题,因为并不是每个人都会遇到这种情况,只有少数客户和开发人员会遇到这个问题。

    如果您仅在 chrome(或具有相同引擎的浏览器)中遇到此问题,您可以尝试将 chrome 上的此标志设置为禁用。

    这里发生的情况是,chrome 具有不同的安全规则,即“如果在没有 Secure 属性的情况下设置了没有 SameSite 限制的 cookie,它将被拒绝”。所以你可以禁用这个规则,它会起作用。

    或者,您也可以设置 Secure 属性,但我不知道该怎么做;(

    【讨论】:

    • 不确定过去 7 天发生了什么,今天本地一切正常,但现在不行。我禁用了同样的标志,现在一切正常。
    • 这个为我修复了错误 IDX21323。根本原因:微软代码示例使用https(端口443),我自己的项目使用http(端口80)。为避免不得不更改 Chrome 标志,您的开发网络服务器需要通过 https 访问。
    【解决方案2】:

    检查 AD 应用注册 --> 设置 --> 回复 URL 中提到的 URL。例如,如果该网址是https://localhost:44348/

    转到 MVC 项目 --> 属性(右键单击和属性) --> Web 部分 --> 开始 URL 和项目 URL 也应该是 https://localhost:44348/

    这已经为我解决了这个问题。其他选项是在 Startup.Auth 中的 AD 身份验证后动态设置重定向 URL

    【讨论】:

    • 这解决了我的问题;我一直在通过localhost:8080 在服务器上进行本地测试,但是我之前将回复 URL 设置为实际域名,并且没有localhost:8080。测试时我使用的是 localhost URL - 这导致了这个错误。谢谢@Narasimha Rao Dattappa
    【解决方案3】:

    How to solve IDX21323

    这行代码解决了问题,错误的原因是ASP.NET还没有创建会话信息。函数“authFailed.OwinContext.Authentication.Challenge()”用身份验证所需的信息填充标题。


            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);
                }
            }
        });
    

    【讨论】:

    • 请添加一些关于此代码如何回答问题的说明以改进您的答案。
    • 这不是一个解决方案,而是一个 hack
    • 在我的例子中,原因是登录后点击了浏览器的返回按钮。这会导致使用缓存的 NONCE,然后导致 IDX21323 错误。简单地发出另一个 OwinContext.Authentication.Challenge() 将创建一个“新鲜”的 NONCE 对我来说似乎并不是什么大问题。
    • 我必须添加一些行才能工作并让我再次登录。 context.HandleResponse(); var url = context.Request.Uri.ToString(); context.OwinContext.Response.Redirect(url);
    • 这来自 Microsoft Docs,正是您所说的,也许不是黑客:docs.microsoft.com/en-us/answers/questions/137574/…
    【解决方案4】:

    请参阅 Chris Ross 的 System.Web response cookie integration issues(github 上的又名 Tratcher)。 OWIN cookie 管理器和 ASP.NET Framework 中内置的原始 cookie 管理可能会以无益的方式发生冲突,并且没有通用的解决方案。但是,在设置 OIDC 身份验证时,我发现该链接中建议的解决方法对我有用:

    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
       // ...
       CookieManager = new SystemWebCookieManager()
    });
    

    还有:

    OpenIdConnectAuthenticationOptions.CookieManager = new SystemWebCookieManager();
    

    这会导致 OWIN 使用 ASP.NET Framework cookie jar/store 并避免冲突。我想他会有副作用,所以小心行事!阅读链接以获得完整说明。

    【讨论】:

    • 我只设置了OpenIdConnectAuthenticationOptions.CookieManager = new SystemWebCookieManager(); 并且有效
    • 这个也适用于我。谢谢!
    【解决方案5】:

    由于不一致,我相信您看到的错误是由人们所说的“Katana bug #197”引起的。

    幸运的是,有一个名为 Kentor.OwinCookieSaver 的 nuget 包的解决方法。

    安装 nuget 包后,在 app.UseCookieAuthentication(cookieOptions); 之前添加 app.UseKentorOwinCookieSaver();。

    欲了解更多信息,请查看Kentor.OwinCookieSaver repo on GitHub。

    【讨论】:

    • 此包 Kentor.OwinCookieSaver 已被弃用。
    【解决方案6】:

    还请检查此链接: https://docs.microsoft.com/en-us/aspnet/samesite/owin-samesite

    对我来说,起初它不起作用,但解决方案是使用 https。我使用了 Visual Studio IIS Express,它使用 http 托管网站默认值。在测试中它因为 https 而工作。

    【讨论】:

      【解决方案7】:

      我的开始和项目 URL 与 Azure 中的重定向 URI 不同。我完成了所有这些匹配,不再出现 IDX2132 错误。

      【讨论】:

        【解决方案8】:

        我在生产环境中遇到了同样的错误,而在本地它适用于所有开发团队。我已经尝试过 Michael Flanagan 建议的 Kentor.OwinCookieSaver 解决方案,但它没有帮助。经过一番挖掘,我发现身份验证本身已成功完成,并且 OwinContext 包含用户身份和声明,但是 AuthenticationFailed 事件处理程序引发了 IDX21323 异常。所以我决定使用以下解决方法 - 我更新了 AuthenticationFailed 事件处理程序:

        // 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);
        

        这样系统不会抛出IDX21323异常,而是继续认证过程,允许用户登录和使用系统。

        我知道这不是解决方案,但至少用户现在可以登录,直到我找到解决此问题的更好方法。

        【讨论】:

          【解决方案9】:

          Azure 问题?

          确保您使用的是正确的域名。我正在调试 Azure 上的一些防火墙问题,我正在使用 my-subdomain.azurewebsites.net 来查看站点本身是否已启动,一旦启动,我就忘记将域名改回 my-subdomain.mydomainname.org。

          【讨论】:

            猜你喜欢
            • 2021-09-28
            • 2021-11-10
            • 1970-01-01
            • 2020-08-12
            • 1970-01-01
            • 2017-06-15
            • 2018-01-14
            • 1970-01-01
            相关资源
            最近更新 更多