OpenIDConnect认证报错IDX21323:本地HTTP环境下如何解决?
按照Stack Overflow教程《Validate Azure AD token in a .NET 4.7 API without messing actual validation》实现Azure AD令牌验证时,仅将示例代码中的HTTPS改为HTTP,登录后触发IDX21323错误:
Error: IDX21323: RequireNonce is 'System.Boolean'. 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.
使用的Startup.cs代码如下:
using System; using System.Threading.Tasks; using Microsoft.Owin; using Owin; using Microsoft.IdentityModel.Protocols.OpenIdConnect; using Microsoft.IdentityModel.Tokens; using Microsoft.Owin.Security; using Microsoft.Owin.Security.Cookies; using Microsoft.Owin.Security.OpenIdConnect; using Microsoft.Owin.Security.Notifications; [assembly: OwinStartup(typeof(AppModelv2_WebApp_OpenIDConnect_DotNet.Startup))] namespace AppModelv2_WebApp_OpenIDConnect_DotNet { public class Startup { // The Client ID is used by the application to uniquely identify itself to Azure AD. string clientId = System.Configuration.ConfigurationManager.AppSettings["ClientId"]; // RedirectUri is the URL where the user will be redirected to after they sign in. string redirectUri = System.Configuration.ConfigurationManager.AppSettings["RedirectUri"]; // Tenant is the tenant ID (e.g. contoso.onmicrosoft.com, or 'common' for multi-tenant) static string tenant = System.Configuration.ConfigurationManager.AppSettings["Tenant"]; // Authority is the URL for authority, composed by Microsoft identity platform endpoint and the tenant name (e.g. https://login.microsoftonline.com/contoso.onmicrosoft.com/v2.0) string authority = String.Format(System.Globalization.CultureInfo.InvariantCulture, System.ConfigurationManager.AppSettings["Authority"], tenant); /// <summary> /// Configure OWIN to use OpenIdConnect /// </summary> /// <param name="app"></param> public void Configuration(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { // Sets the ClientId, authority, RedirectUri as obtained from web.config ClientId = clientId, Authority = authority, RedirectUri = redirectUri, // PostLogoutRedirectUri is the page that users will be redirected to after sign-out. In this case, it is using the home page PostLogoutRedirectUri = redirectUri, Scope = OpenIdConnectScope.OpenIdProfile, // ResponseType is set to request the code id_token - which contains basic information about the signed-in user ResponseType = OpenIdConnectResponseType.CodeIdToken, // OpenIdConnectAuthenticationNotifications configures OWIN to send notification of failed authentications to OnAuthenticationFailed method Notifications = new OpenIdConnectAuthenticationNotifications { AuthenticationFailed = OnAuthenticationFailed } } ); } /// <summary> /// Handle failed authentication requests by redirecting the user to the home page with an error in the query string /// </summary> /// <param name="context"></param> /// <returns></returns> private Task OnAuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context) { context.HandleResponse(); context.Response.Redirect("/?errormessage=" + context.Exception.Message); return Task.FromResult(0); } } }
输入AD凭据后触发OnAuthenticationFailed方法,需解决以下问题:
- 缺失了什么配置?
- 本地主机是否必须使用SSL/HTTPS?
- 若必须使用HTTPS,能否在本地HTTP环境下正常工作?
(使用Visual Studio 2015)
1. 错误核心原因及配置修复
错误本质是nonce验证失败:Azure AD返回的ID Token包含nonce值,但HTTP环境下,默认Cookie的Secure属性会阻止nonce被存储/读取,导致验证时找不到对应值。
修复需显式关闭nonce验证(仅本地开发用,生产必须开启):在OpenIdConnectAuthenticationOptions中添加ProtocolValidator配置:
new OpenIdConnectAuthenticationOptions { // 原有配置保留 ProtocolValidator = new OpenIdConnectProtocolValidator { RequireNonce = false }, // 原有配置保留 }
2. HTTPS的必要性说明
生产环境必须使用HTTPS:OpenID Connect协议要求安全传输通道,Azure AD官方也强制生产环境重定向URI为HTTPS。
本地开发可临时用HTTP,但需额外调整Cookie配置,允许非HTTPS环境存储Cookie:
app.UseCookieAuthentication(new CookieAuthenticationOptions { CookieSecure = CookieSecureOption.Never });
3. 本地HTTP环境完整配置示例
修改后的Startup.cs关键代码片段:
public void Configuration(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); // 调整Cookie认证允许HTTP环境 app.UseCookieAuthentication(new CookieAuthenticationOptions { CookieSecure = CookieSecureOption.Never }); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { ClientId = clientId, Authority = authority, RedirectUri = redirectUri, PostLogoutRedirectUri = redirectUri, Scope = OpenIdConnectScope.OpenIdProfile, ResponseType = OpenIdConnectResponseType.CodeIdToken, // 关闭nonce验证 ProtocolValidator = new OpenIdConnectProtocolValidator { RequireNonce = false }, Notifications = new OpenIdConnectAuthenticationNotifications { AuthenticationFailed = OnAuthenticationFailed } }); }
注意事项
- 上述配置仅适用于本地开发调试,上线时必须恢复为HTTPS:移除
ProtocolValidator配置(或设RequireNonce = true),并将CookieSecure改为CookieSecureOption.Always。 - 需在Azure AD应用注册中,添加对应的HTTP重定向URI(如
http://localhost:xxxx/)。
内容的提问来源于stack exchange,提问作者Developer

