You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 8中通过OpenID Connect连接AzureAD异常问题

解决.NET 8升级后AzureAD OpenID Connect连接失效问题

问题根源

从错误日志能看到,中间件请求的元数据地址是https://login.microsoftonline.com/v2.0/.well-known/openid-configuration——实际租户ID被丢失,v2.0被错误识别为租户ID,这才触发了AADSTS90002错误。

这是因为.NET 8对OpenIdConnectOptions.Authority的解析逻辑做了调整:当Authority末尾带有斜杠时,中间件会错误截取路径最后一段作为租户标识,导致元数据地址拼接错误。而.NET 7的解析逻辑不会出现这个问题。

修复方案

方案1:修正Authority格式(推荐)

去掉Authority末尾的斜杠,让中间件正确解析租户ID和版本路径:

// 原代码(末尾带斜杠)
// options.Authority = $"https://login.microsoftonline.com/{oidcTenantId}/v2.0/";

// 修改后(去掉末尾斜杠)
options.Authority = $"https://login.microsoftonline.com/{oidcTenantId}/v2.0";

方案2:显式指定MetadataAddress

如果方案1不生效,直接手动指定正确的元数据地址,绕过中间件的自动解析:

// 取消注释并保留正确格式
options.MetadataAddress = $"https://login.microsoftonline.com/{oidcTenantId}/v2.0/.well-known/openid-configuration";

修改后的完整代码示例

authenticationBuilder.AddOpenIdConnect(authenticationScheme: "AzureAd", displayName: "Azure Active Directory", options =>
{
    string oidcInstance = configuration["AzureAd:Instance"]!;
    string oidcDomain = configuration["AzureAd:Domain"]!;
    string oidcClientId = configuration["AzureAd:ClientId"]!;
    string oidcTenantId = configuration["AzureAd:TenantId"]!;
    string oidcClientSecret = configuration["AzureAd:ClientSecret"]!;

    // 修正Authority格式,去掉末尾斜杠
    options.Authority = $"https://login.microsoftonline.com/{oidcTenantId}/v2.0";
    options.RequireHttpsMetadata = false;
    options.ClientId = oidcClientId;
    options.ClientSecret = oidcClientSecret;
    options.ResponseType = OpenIdConnectResponseType.CodeIdToken;
    options.TokenValidationParameters.IssuerValidator = AadIssuerValidator.GetAadIssuerValidator(oidcInstance).Validate;
    options.GetClaimsFromUserInfoEndpoint = true;
    options.MapInboundClaims = false;
    options.TokenValidationParameters.NameClaimType = "name";
    options.CallbackPath = new PathString("/signin-oidc");
    options.SignedOutCallbackPath = new PathString("/signout-callback-oidc");
    options.RemoteSignOutPath = new PathString("/signout-oidc");

    // 可选:显式指定MetadataAddress确保地址正确
    options.MetadataAddress = $"https://login.microsoftonline.com/{oidcTenantId}/v2.0/.well-known/openid-configuration";

    options.Events.OnUserInformationReceived = async userInformationReceivedContext =>
    {
        //...
    };
});

验证要点

  • 确认oidcTenantId配置项正确读取到了实际租户ID(而非v2.0)
  • 测试时可开启日志,检查中间件实际请求的元数据地址是否包含正确租户ID

内容的提问来源于stack exchange,提问作者Sandy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 02:23:17