[已解决][Asp.net core] 项目使用 Swagger UI 5.0.0-rc5, 无法将 Bearer token 添加Authentication Header.

[已解决][Asp.net core] 项目使用 Swagger UI 5.0.0-rc5, 无法将 Bearer token 添加Authentication Header.

github issure: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1425

官方doc: https://docs.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-3.1&tabs=visual-studio

环境信息

  • .net core 3.1
  • Swashbuckle.AspNetCore -Version 5.0.0-rc4

问题描述

asp.net core web api 项目配置了 jwt Authentication 后. 部分 api 通过[Authorize] 标签配置成为需要 http request 中需要带有 bearer token 的 header. 之前项目同样配置了 swagger 中间件, 一般用于后端开发测试 API 使用. 但是按照官方文档配置的 swagger UI 本身是不带有配置 header 的功能的. 在旧版本中一般是通过添加

// startup.cs
options.OperationFilter<SwaggerHeaderFilter>();

//filter code
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
    var filterDescriptors = context.ApiDescription.ActionDescriptor.FilterDescriptors;
    var isAuthorized = filterDescriptors.Select(filterInfo => filterInfo.Filter).Any(filter => filter is AuthorizeFilter);
    var allowAnonymous = filterDescriptors.Select(filterInfo => filterInfo.Filter).Any(filter => filter is IAllowAnonymousFilter);

    if (isAuthorized && !allowAnonymous)
    {
        if (operation.Parameters == null)
        {
            operation.Parameters = new List<OpenApiParameter>();
        }

        operation.Parameters.Add(new OpenApiParameter
        {
            Name = "Authorization",
            In = ParameterLocation.Header,
            Description = "access token",
            Required = true,
            Schema = new OpenApiSchema
            {
                Type = "string",
                Default = new OpenApiString("Bearer {access token}"),
            }
        });

        operation.Responses.Add("401", new OpenApiResponse { Description = "Unauthorized" });
        operation.Responses.Add("403", new OpenApiResponse { Description = "Forbidden" });
    }
}

在有[Authorize]声明的 Action 上添加一个可以输入 token 的控件. 但是配置后经过测试并不好用.

解决方案

目前以下的 startup.cs 配置方案对于我是 work 的.所以我直接贴出来以供参考

// Register the Swagger generator, defining 1 or more Swagger documents
services.AddSwaggerGen(options =>
{
    options.SwaggerDoc("v1", new OpenApiInfo{ Version = "v1", });
    //options.OperationFilter<SwaggerHeaderFilter>();

    options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        Description = "JWT Authorization header using the Bearer scheme.",
        Name = "Authorization",
        In = ParameterLocation.Header,
        Scheme = "bearer",
        Type = SecuritySchemeType.Http,
        BearerFormat = "JWT"
    });

    options.AddSecurityRequirement(new OpenApiSecurityRequirement
        {
            {
                new OpenApiSecurityScheme
                {
                    Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }
                },
                new List<string>()
            }
        });
});

在右上角会出现认证button, 如图

先通过无需认证的 Auth API 获取 token 信息:

然后复制 token, 点击认证 button, 输入 token, 认证成功:

认证后, 测试一个需要认证通过方能访问的 API, 我将 GetCategories 设置成为需要认证的 API, 然后通过 swagger UI 测试可以获取得到数据:

OK 解决了. 希望以上内容能够帮助到遇到同样问题的你.

猜你喜欢

转载自www.cnblogs.com/it-dennis/p/12170454.html