[已解決][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 解決了. 希望以上內容能夠幫助到遇到同樣問題的你.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM