.NET Framework对接AADB2C时AuthorizationCodeReceived事件中AuthenticationTicket为空
问题根因
你当前配置的ResponseType = "code"是纯授权码流,该模式下身份提供商仅返回授权码,OIDC中间件没有可用于验证身份的id_token,自然无法提前生成AuthenticationTicket,所以该属性为null是符合预期的。
解决方案1(推荐):调整响应类型同时返回ID令牌
修改OpenIdConnectAuthenticationOptions的ResponseType配置,改为同时返回授权码和ID令牌:
ResponseType = "code id_token",
修改后需要同步调整AAD B2C应用注册配置:进入你对应的B2C应用注册 → 「身份验证」菜单 → 勾选「ID令牌(用于隐式流和混合流)」选项并保存。
配置完成后OIDC中间件会在回调时先验证返回的id_token,自动生成AuthenticationTicket,你在AuthorizationCodeReceived事件中就能正常读取该属性。
解决方案2:保留纯code流,手动构造AuthenticationTicket
如果你必须使用纯授权码流,可在AuthorizationCodeReceived事件中先完成授权码兑换,再手动构造身份票据:
AuthorizationCodeReceived = async notification => { // 1. 构建兑换code的请求参数 var tokenRequestParameters = new Dictionary<string, string> { {"client_id", _azureAdClientId}, {"code", notification.Code}, {"grant_type", "authorization_code"}, {"redirect_uri", notification.RedirectUri}, {"scope", "openid profile offline_access"} }; // 2. 请求B2C令牌端点兑换令牌 var httpClient = _httpClientFactory.CreateClient(HttpClientNames.Owin); var tokenResponse = await httpClient.PostAsync( $"{_azureAdInstance}/{_azureAdTenant}/{_azureAdB2CPolicy}/oauth2/v2.0/token", new FormUrlEncodedContent(tokenRequestParameters)); var tokenContent = await tokenResponse.Content.ReadFromJsonAsync<TokenResponse>(); // 自行定义TokenResponse类接收返回的id_token、access_token、refresh_token等 // 3. 验证id_token并构造ClaimsIdentity var tokenHandler = new JwtSecurityTokenHandler(); var validationParameters = notification.Options.TokenValidationParameters.Clone(); // 可补充必要的验证参数配置 var claimsPrincipal = tokenHandler.ValidateToken(tokenContent.IdToken, validationParameters, out _); // 4. 手动赋值AuthenticationTicket notification.AuthenticationTicket = new AuthenticationTicket( (ClaimsIdentity)claimsPrincipal.Identity, claimsPrincipal.Properties, notification.Options.AuthenticationType); // 后续业务逻辑 }
其他注意排查点
- 确保应用注册中配置的
RedirectUri和代码中配置的完全一致,包括协议、域名、路径、结尾斜杠,否则会出现code兑换失败问题 - 确保
Scope配置中包含openid,这是获取ID令牌的必要条件 - 如果开启了
ValidateIssuer,请确保ValidIssuers配置正确,否则ID令牌验证失败也会导致AuthenticationTicket为空
内容的提问来源于stack exchange,提问作者Johan Blomgren
相关产品推荐
相关产品推荐

