通过 OpenID Connect 连接到 AzureAd 似乎在 .NET 8 中无法正常工作

问题描述 投票:0回答:1

我刚刚将项目从 .NET 7 升级到 .NET 8,OpenID Connect 到 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;包含子域

X-内容类型-选项:nosniff

访问控制允许来源:*

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

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

x-ms-请求-id:4379b336-fe23-4d6c-95c6-d71717573e00

x-ms-ests-服务器:2.1.16790.7 - SCUS ProdSlices

X-XSS-保护:0

设置Cookie:fpc=Av3iPXMPIHBMgE-fomXi7KM;过期=2023 年 12 月 17 日星期日 格林威治标准时间 02:58:22;路径=/;安全的;仅 Http;相同站点=无

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

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

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

内容长度:649

}', HttpResponseMessage.Content: '{“错误”:“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],"时间戳":"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 azure-active-directory openid-connect .net-8.0
1个回答
0
投票

我尝试使用你的代码,即使我得到了像你一样的类似错误代码。

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"    
  };
  • 现在我可以毫无问题地访问该应用程序了。

我完整的

Program.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

© www.soinside.com 2019 - 2024. All rights reserved.