ASP.NET Core Web API:尝试从 Azure AD 授权用户时出现 CORS 错误

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

我正在尝试设置一个基于 .NET Core 的开源应用程序,下面是我下载的应用程序源代码的路径。

https://gitlab.com/sis-cc/.stat-suite/dotstatsuite-core-auth-management

当我在

appsettings.json
文件中禁用身份验证时,我能够成功运行应用程序并命中端点,我现在尝试启用身份验证,为此我对
appsettings.json
文件进行了更改,我更改了数据库连接、权限值、授权url、范围值等

{
    "DotStatSuiteCoreCommonDbConnectionString": "Data Source=dbserver;Initial Catalog=DotStat.Common;User ID=USERNAME;Password=XXXXXX",
    "AutoLog2Google": false,
    "GoogleLogLevel": "Debug",
    "GoogleProjectId": "XXXX",
    "GoogleLogId": "AUTH_SERVICE",
    "auth": {
        "enabled":true,
        "authority": "https://login.microsoftonline.com/cdk.org/",
        "clientId": "xxxxx-xxxx-xxxxxx",
        //"requireHttps": true,
        "validateIssuer": true,
        "claimsMapping": {
            "email": "email",
            "groups": "groups"
        },
        "authorizationUrl": "https://login.microsoftonline.com/21adghhrr-345sdg-4534645dfgfdgh/oauth2/v2.0/authorize",
        "tokenUrl": "",
        "scopes": [ "user.read" ]
    }
}

我已将应用程序部署到 Azure 应用程序,现在当我尝试访问 Swagger URL 时,Swagger 页面会加载,并且在主页上单击授权选项卡并选择范围“user.read”复选框并单击授权选项卡,我收到此错误:

从源“https://dotstatauthservicedev.ites.cdk.org”获取“https://login.microsoftonline.com/21adghhrr-345sdg-4534645dfgfdgh/oauth2/v2.0/authorize”的访问已被 CORS 阻止策略:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以在禁用 CORS 的情况下获取资源

我的理解是,当我们单击“授权”按钮时,Swagger 将向 Azure 活动目录的 AuthorizationUrl 发出请求,以对用户进行身份验证,并且作为响应,我应该获得一个可用于调用 API 端点的令牌。

关于如何解决这个问题有什么建议吗?

oauth-2.0 azure-active-directory asp.net-core-webapi swagger-ui
1个回答
0
投票

无论如何,你的代码在我这边不起作用,请允许我分享我的工作示例。我有一个集成 Azure AD 的 asp.net core Web api 应用程序来保护我的 API。这是我的 Program.cs。与您的代码相比,我测试使用

AuthorizationCode
作为流程,但它对我不起作用。与此同时,您的代码中的
TokenUrl
可能有问题。您没有在应用程序设置中为
 "tokenUrl": "",
定义值,因此该行
TokenUrl = new Uri(string.IsNullOrEmpty(_auth.TokenUrl) ? _auth.AuthorizationUrl.Replace("openid-connect/auth", "openid-connect/token") : _auth.TokenUrl),
不适合您,因为
AuthorizationUrl
中没有
openid-connect

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
using Microsoft.Identity.Web;
using Microsoft.OpenApi.Models;
using System.Reflection;
using System.Security.AccessControl;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApplication1", Version = "v1" });
    c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
    {
        Type = SecuritySchemeType.OAuth2,
        Flows = new OpenApiOAuthFlows()
        {
            Implicit = new OpenApiOAuthFlow()
            {
                AuthorizationUrl = new Uri("https://login.microsoftonline.com/tenant_id/oauth2/v2.0/authorize"),
                TokenUrl = new Uri("https://login.microsoftonline.com/tenant_id/oauth2/v2.0/token"),
                Scopes = new Dictionary<string, string> {
                    {
                        "api://clientId/Tiny.Read", "API permission description"
                    }
                }
            }

        }
    });
    c.AddSecurityRequirement(new OpenApiSecurityRequirement() {
        {
            new OpenApiSecurityScheme {
                Reference = new OpenApiReference {
                    Type = ReferenceType.SecurityScheme,
                    Id = "oauth2"
                },
                Scheme = "oauth2",
                Name = "oauth2",
                In = ParameterLocation.Header
            },
            new List < string > ()
        }
    });
});

var app = builder.Build();
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(options =>
    {
     options.OAuthAppName("Swagger Client");
     options.OAuthClientId("{client_id}");
     options.OAuthClientSecret("{client_secret}");
     options.OAuthUseBasicAuthenticationWithAccessCodeGrant();
    });
}

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

我的测试结果。

enter image description here

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