ASP.NET Core API:身份验证弹出窗口未显示在 Swagger UI 中 [英] ASP.NET Core API: Authentication popup is not showing up in Swagger UI

查看:113
本文介绍了ASP.NET Core API:身份验证弹出窗口未显示在 Swagger UI 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 Swashbuckle 集成 Swagger 的 ASP.NET Core Web API.我已使用操作过滤器在 Swagger UI 上成功集成授权,因为我不想为匿名 API 显示挂锁.

I have an ASP.NET Core Web API with Swagger integrated using Swashbuckle. I have successfully integrated authorization on Swagger UI using an operation filter, because I do not want to show padlock for anonymous APIs.

.OperationFilter<AuthorizeFilter>()

在过滤器中,我已经为 Swagger UI 注册了基本的身份验证安全要求.

Inside the filter, I have registered basic auth security requirement for Swagger UI.

我的问题是,即使在 Swagger UI 上的 API 中进行了身份验证,我也不再看到单击挂锁图标时出现的漂亮的身份验证弹出窗口.

My problem is, even though authentication is happening in APIs on Swagger UI, I no longer see that nice authentication popup which is giving when click on the padlock icon.

有人可以回答,为什么我现在没有看到身份验证弹出窗口?

Could someone answer, why I am not seeing the auth popup now?

推荐答案

假设您有一些使用 [Authorize] 属性保护的端点(也可以放在控制器上).

Assuming you have some endpoints that protected with [Authorize] attribute (can also be put on the controller).

[Route("")]
public class HelloController : ControllerBase
{
    [Authorize]
    [HttpGet("secure")]
    public IActionResult GetSomethingPrivate()
    {
        return Ok("secret");
    }

    [HttpGet("public")]
    public IActionResult GetSomethingPublic()
    {
        return Ok("hey");
    }
}

您需要定义适合您需求的安全方案.但不要全局要求它,而是将其添加到操作过滤器中.在这里,我添加了一个简单的令牌身份验证:

You need to define a security scheme suitable for your needs. But do not require it globally, instead add it inside an operation filter. Here I've added a simple token auth:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "ApiPlayground", Version = "v1" });
        c.AddSecurityDefinition("token", new OpenApiSecurityScheme
        {
            Type = SecuritySchemeType.ApiKey,
            In = ParameterLocation.Header,
            Name = HeaderNames.Authorization,
            Scheme = "Bearer"
        });
        // dont add global security requirement
        // c.AddSecurityRequirement(/*...*/);
        c.OperationFilter<SecureEndpointAuthRequirementFilter>();
    });
}

这是引用我们刚刚创建的 token 身份验证方案的操作过滤器.它检查端点是否需要身份验证,然后添加要求.

And here's the operation filter which references the token auth scheme we've just created. It checks if the endpoint needs authentication, then adds the requirement.

internal class SecureEndpointAuthRequirementFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        if (!context.ApiDescription
            .ActionDescriptor
            .EndpointMetadata
            .OfType<AuthorizeAttribute>()
            .Any())
        {
            return;
        }

        operation.Security = new List<OpenApiSecurityRequirement>
        {
            new OpenApiSecurityRequirement
            {
                [new OpenApiSecurityScheme
                {
                    Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "token" }
                }] = new List<string>()
            }
        };
    }
}

当您运行应用程序时,它会按您的预期工作:

When you run the app, it works as you expect:

auth 弹出窗口也是如此:

So does the auth popup:

使用以下值定义新的安全方案:

Define a new security scheme with following values:

public void ConfigureServices(IServiceCollection services)
{
    // ...
    services.AddSwaggerGen(c =>
    {
        // ...
        // basic auth scheme (username + password)
        c.AddSecurityDefinition("basic", new OpenApiSecurityScheme
        {
            Type = SecuritySchemeType.Http,
            Scheme = "basic"
        });
        // dont add global security requirement
        // c.AddSecurityRequirement(/*...*/);
        c.OperationFilter<SecureEndpointAuthRequirementFilter>();
    });
}

然后更新操作过滤器以引用basic auth scheme:

Then update the operation filter to reference basic auth scheme:

internal class SecureEndpointAuthRequirementFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        if (!context.ApiDescription
            .ActionDescriptor
            .EndpointMetadata
            .OfType<AuthorizeAttribute>()
            .Any())
        {
            return;
        }

        operation.Security = new List<OpenApiSecurityRequirement>
        {
            new OpenApiSecurityRequirement
            {
                [new OpenApiSecurityScheme
                {
                    Reference = new OpenApiReference
                    {
                        Type = ReferenceType.SecurityScheme, 
                        Id = "basic" // <-- changed "token" -> "basic"
                    }
                }] = new List<string>()
            }
        };
    }
}

身份验证弹出窗口的外观如下:

here's how the auth popup looks:

登录后,请求包含正确的Authorization 标头.

After logging in, requests include the correct Authorization header.

这篇关于ASP.NET Core API:身份验证弹出窗口未显示在 Swagger UI 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆