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

标签 c# azure asp.net-core swagger swashbuckle

我正在尝试使用 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")
        }
    }
});

关于c# - .NET Core Web Api Azure AD 和 Swagger 未进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58589312/

相关文章:

c# - 我应该将服务注入(inject)到我的 MVC View 中吗?

azure - 获取一年中的第几周 - Azure 数据工厂中的表达式和函数

c# - 如何在应用程序目录层次结构中构建接口(interface)?

c# - 带外键的 Fluent nHibernate "not-null property references a null or transient value"

sql - 复制 Azure SQL 数据库并更改规模

azure - SSL 证书 - 在 Azure KeyVault 中导入根和链?

c# - ASP vNext 和 PostgreSql

c# - 解析值 : . 路径 '' 时遇到意外字符,第 1 行,位置 1

security - 使用多种身份验证方法的 ASP.NET Core

c# - vs201 0 auto 化: Get the text value of a EnvDTE. CodeElement