在 .NET 8 中,通过 OpenID Connect 连接到 AzureAd 似乎已中断

Connecting to AzureAd through OpenID Connect seems broken in .NET 8

提问人:Sandy 提问时间:11/17/2023 最后编辑:HarshithaSandy 更新时间:11/17/2023 访问量:96

问:

我刚刚将我的项目从 .NET 7 升级到 .NET 8,OpenID Connect to AzureAD 停止工作。以下代码适用于 .NET 7:

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"]!;

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

              //Setting the following has no effect.
              //options.MetadataAddress = $"https://login.microsoftonline.com/{oidcTenantId}/v2.0/.well-known/openid-configuration";

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

我在 .NET 8 中出现以下错误:

IOException:IDX20807:无法从以下位置检索文档: “https://login.microsoftonline.com/v2.0/.well-known/openid-configuration”。 HttpResponseMessage:'状态代码:400,ReasonPhrase:'错误请求', 版本: 1.1, 内容: System.Net.Http.HttpConnectionResponseContent, 头:

{

缓存控制:私有

严格传输安全:max-age=31536000;includeSubDomains

X-Content-Type-Options:嗅探

访问控制允许源:*

访问控制允许方法:GET、OPTIONS

P3P:CP=“DSP CUR OTPi IND OTRi ONL FIN”

X-MS 请求 ID:4379B336-FE23-4D6C-95C6-D71717573E00

x-ms-ests-server:2.1.16790.7 - SCUS ProdSlices

X-XSS 保护:0

设置Cookie:fpc=Av3iPXMPIHBMgE-fomXi7KM;expires=星期日, 17-Dec-2023 格林威治标准时间02:58:22;路径=/;安全;HttpOnly的;SameSite=无

设置Cookie:x-ms-gateway-slice=estsfd;路径=/;安全;httponly

日期:2023 年 11 月 17 日星期五 02:58:21 GMT

内容类型:application/json;字符集=utf-8

内容长度:649

}', HttpResponseMessage.Content: '{“error”:“invalid_tenant”,“error_description”:“AADSTS90002:租户 未找到“v2.0”。检查以确保你具有正确的租户 ID 并且正在登录到正确的云。检查您的订阅 管理员,如果没有活动订阅,可能会发生这种情况 对于租户。跟踪 ID:4379b336-fe23-4d6c-95c6-d71717573e00 相关 ID:0c5cf6f7-311f-4122-a547-aaee24d3159e 时间戳: 2023-11-17 02:58:22Z“,”error_codes“:[90002],”timestamp“:”2023-11-17 02:58:22Z“,”trace_id“:”4379b336-fe23-4d6c-95c6-d71717573e00“,”correlation_id“:”0c5cf6f7-311f-4122-a547-aaee24d3159e“,”error_uri“:”https://login.microsoftonline.com/error?code=90002“}'.

任何帮助将不胜感激。

C# Azure-Active-Directory OpenID-Connect net-8.0

评论

0赞 gunr2171 11/17/2023
“无法从以下位置检索文档:'login.microsoftonline.com/v2.0/.well-known/....”该 url 是否实际包含租户 ID,或者是拼写错误/审查器?
0赞 Sandy 11/17/2023
我没有修改错误消息。所以我的猜测是租户 ID 不会发送到服务器。
0赞 Harshitha 11/17/2023
您是在本地还是在 Azure 中遇到问题?
1赞 Sandy 11/17/2023
该项目尚未部署。因此,该错误发生在本地开发计算机上的 Visual Studio 中。
0赞 Harshitha 11/17/2023
您正在使用的 Visual Studio 版本是什么?

答:

1赞 Harshitha 11/17/2023 #1

我尝试使用您的代码,即使我收到像您一样的类似错误代码。

IOException: IDX20807: Unable to retrieve document from:
InvalidOperationException: IDX20803: Unable to obtain configuration from: 'https://login.microsoftonline.com/v2.0/.well-known/openid-configuration'.
  • 问题似乎在于传递 .TokenValidationParameters
  • 删除了以下代码行
options.TokenValidationParameters.IssuerValidator = AadIssuerValidator.GetAadIssuerValidator(oidcInstance).Validate; 
options.TokenValidationParameters.NameClaimType = "name";
  • 并添加如下。TokenValidationParameters
  options.TokenValidationParameters = new TokenValidationParameters
  {
      NameClaimType = "name"    
  };
  • 现在我能够毫无问题地访问该应用程序。

我的完整程序.cs文件:

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using Microsoft.IdentityModel.Validators;

var builder = WebApplication.CreateBuilder(args);


builder.Services.AddAuthentication(options =>
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
    .AddCookie()
    .AddOpenIdConnect(options =>
    {
        string oidcInstance = builder.Configuration["AzureAd:Instance"]!;
        string oidcDomain = builder.Configuration["AzureAd:Domain"]!;
        string oidcClientId = builder.Configuration["AzureAd:ClientId"]!;
        string oidcTenantId = builder.Configuration["AzureAd:TenantId"]!;
        string oidcClientSecret = builder.Configuration["AzureAd:ClientSecret"]!;

        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.TokenValidationParameters = new TokenValidationParameters
        {
            NameClaimType = "name",
        };

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

builder.Services.AddRazorPages()
    .AddMicrosoftIdentityUI();

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapRazorPages();
app.MapControllers();
app.Run();

输出: enter image description here

评论

1赞 Sandy 11/18/2023
这也为我解决了问题。谢谢!!!你知道删除的代码行有什么作用吗 - 我失去了什么功能?选项。TokenValidationParameters.IssuerValidator = AadIssuerValidator.GetAadIssuerValidator(oidcInstance)。驗證;
0赞 Harshitha 11/18/2023
不要担心删除的行。我刚刚更改了我建议的那行代码调用 TokenValidationParameters.Comment 的方式。您可以看到 hello 旁边缺少该名称。登录后。
0赞 Harshitha 11/18/2023
它设置 name 的值。