.NET Core Web Api Azure AD 和 Swagger 未进行身份验证

.NET Core Web Api Azure AD and Swagger not authenticating

我正在尝试使用 Azure AD 身份验证和 Swagger 设置 .NET Core Web API,但在尝试进行身份验证时出现错误。

我正在遵循此指南:http://www.sharepointconfig.com/2018/08/configure-swagger-to-authenticate-against-azure-ad/

ConfigureServices 包含此代码:

        services.AddSwaggerGen(c =>
        {
            c.AddSecurityDefinition("oauth2", //Name the security scheme
                   new OpenApiSecurityScheme
                   {
                       Type = SecuritySchemeType.OAuth2,
                       Flows = new OpenApiOAuthFlows() { Implicit = new OpenApiOAuthFlow() },
                       Scheme = "oauth2",
                       OpenIdConnectUrl = new Uri($"https://login.microsoftonline.com/" + _configuration["AzureAD:TenantId"] + "/oauth2/authorize"),
                   });
            c.AddSecurityRequirement(new OpenApiSecurityRequirement{
            {
                new OpenApiSecurityScheme{
                    Reference = new OpenApiReference{
                        Id = "oauth2",
                        Type = ReferenceType.SecurityScheme
                    }
                },new List<string>()
                }
            });
        });

配置包含此代码:

                app.UseSwaggerUI(c =>
            {
                c.OAuthClientId(_configuration["Swagger:ClientId"]);
                c.OAuthClientSecret(_configuration["Swagger:ClientSecret"]);
                c.OAuthRealm(_configuration["AzureAD:ClientId"]);
                c.OAuthAppName("WerfRegistratie V1");
                c.OAuthScopeSeparator(" ");
                c.OAuthAdditionalQueryStringParams(new Dictionary<string, string> { { "resource", _configuration["AzureAD:ClientId"] } });
            });

我一直 运行 解决的问题是这个: Swagger authentication error

看起来当我尝试单击“授权”按钮时,Swagger 中的变量未填写,我一直在 SwaggerUI 中尝试不同的设置,但这种情况一直发生。

我们是这样配置的:

var authority = "https://login.microsoftonline.com/your-aad-tenant-id";
o.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
{
    Type = SecuritySchemeType.OAuth2,
    Flows = new OpenApiOAuthFlows
    {
        Implicit = new OpenApiOAuthFlow
        {
            Scopes = new Dictionary<string, string>
            {
                ["Stuff.Read"] = "Read stuff" // TODO: Replace with your scopes
            },
            AuthorizationUrl = new Uri(authority + "/oauth2/authorize")
        }
    }
});