.NET Core Web Api Azure AD and Swagger not authenticating

大憨熊 提交于 2021-02-11 06:21:15

问题


I am trying to set up a .NET Core Web API with Azure AD authentication and Swagger but it gives an error when trying to authenticate.

I am following this guide: http://www.sharepointconfig.com/2018/08/configure-swagger-to-authenticate-against-azure-ad/

ConfigureServices contains this code:

        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>()
                }
            });
        });

Configure contains this code:

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

The problem I keep running in to is this one: Swagger authentication error

It looks like when I try to click the Authorize button a variable in Swagger is not filled in and I have been trying different settings in the SwaggerUI but this keeps happening.


回答1:


We have configured it like this:

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


来源:https://stackoverflow.com/questions/58589312/net-core-web-api-azure-ad-and-swagger-not-authenticating

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!