使用授权标头(Bearer)设置Swagger(ASP.NET Core)


83

我有一个Web API(ASP.NET Core),我试图调整范围以从中进行调用。调用必须包含Authorization标头,并且我正在使用Bearer身份验证。来自Postman等第三方应用程序的呼叫正常。但是我在设置标题时会遇到麻烦(出于某些原因,我没有收到标题)。现在是这样的:

  "host": "localhost:50352",
  "basePath": "/" ,
  "schemes": [
    "http",
    "https"
  ],
 "securityDefinitions":  {
    "Bearer": {
      "name": "Authorization",
      "in": "header",
      "type": "apiKey",
      "description": "HTTP/HTTPS Bearer"
    }
  },
  "paths": { 
    "/v1/{subAccountId}/test1": {
      "post": {
        "tags": [
          "auth"
        ],
        "operationId": "op1",
        "consumes": ["application/json", "application/html"],
        "produces": ["application/json", "application/html"],
        "parameters": [
          {
            "name": "subAccountId",
            "in": "path",
            "required": true,
            "type": "string"
          }
        ],
        "security":[{
          "Bearer": []
        }],
        "responses": {
          "204": {
            "description": "No Content"
          },
          "400": {
            "description": "BadRequest",
            "schema": {
              "$ref": "#/definitions/ErrorResponse"
            }
          },
          "401": {
            "description": "Unauthorized",
            "schema": {
              "$ref": "#/definitions/ErrorResponse"
            }
          },
          "500": {
            "description": "InternalServerError",
            "schema": {
              "$ref": "#/definitions/ErrorResponse"
            }
          }
        },
        "deprecated": false
      }
    },

Answers:


136

首先,您可以使用Swashbuckle.AspNetCorenuget包自动生成您的招摇定义。(在2.3.0上测试)

安装软件包之后,请在Startup.cs中的ConfigureConfigs方法中进行设置

services.AddSwaggerGen(c => {
    c.SwaggerDoc("v1", new Info { Title = "You api title", Version = "v1" });
    c.AddSecurityDefinition("Bearer",
        new ApiKeyScheme { In = "header",
          Description = "Please enter into field the word 'Bearer' following by space and JWT", 
          Name = "Authorization", Type = "apiKey" });
    c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>> {
        { "Bearer", Enumerable.Empty<string>() },
    });

});

然后,您可以使用页面右上方的“授权”按钮。

至少您可以尝试使用此程序包生成有效的摇头定义


良好的答案,但我做到这一点与ABP样板,它不与动态Web API(工作aspnetboilerplate.com/Pages/Documents/Dynamic-Web-API
Kénium

6
@VadimK直到我升级到.NET Core 2.0为止,它一直运行得很好
monty

10
在这种情况下,在Auth框中的值输入中,您必须准确放置Auth标头,而不仅仅是JWT(在使用JWT的情况下)。这意味着:Bearer your_token_jwt
gatsby

1
确保为令牌添加前缀“ Bearer”。我没有使用Bearer your_token_jwt
PUG

他们做了什么:1. AllowAnonymous 2.角色?
deadManN

134

不推荐使用ApiKeyScheme,在版本5中,您可以像这样使用:

services.AddSwaggerGen(c =>
  {
    c.SwaggerDoc("v1", new Info { Title = "You api title", Version = "v1" });
    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
      {
        Description = @"JWT Authorization header using the Bearer scheme. \r\n\r\n 
                      Enter 'Bearer' [space] and then your token in the text input below.
                      \r\n\r\nExample: 'Bearer 12345abcdef'",
         Name = "Authorization",
         In = ParameterLocation.Header,
         Type = SecuritySchemeType.ApiKey,
         Scheme = "Bearer"
       });

    c.AddSecurityRequirement(new OpenApiSecurityRequirement()
      {
        {
          new OpenApiSecurityScheme
          {
            Reference = new OpenApiReference
              {
                Type = ReferenceType.SecurityScheme,
                Id = "Bearer"
              },
              Scheme = "oauth2",
              Name = "Bearer",
              In = ParameterLocation.Header,

            },
            new List<string>()
          }
        });
    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
    c.IncludeXmlComments(xmlPath);
});

12
可以确认这对于.NET Core 3.0来说像是一种魅力-升级后我在使用.NET Core 2.2时编写的代码不再起作用,而这正是我所需要的
Horkrine

7
要点:i)我需要使用<BR/>而不是\ r \ n才能正确显示消息。ii)代替新的Info {...我需要新的OpenApiInfo {Title ...。[使用swashbuckle.aspnetcore 5.0.0和Microsoft.OpenApi 1.1.4 [.net core 3.1]]
ubienewbie

1
怎么样:1. AllowAnonymous 2.角色?
deadManN

这对我的作品,但描述为“\ r \ n”个部分是不工作...

SecuritySchemeType.ApiKey&的组合Scheme="Bearer"似乎未在Authorization标头的参数中提供任何方案值。与一起使用的任何方案值都会SecuritySchemeType.ApiKey产生格式为的标头{"Authorization","value"}。如果{"Authorization","scheme value"}需要,则应使用SecuritySchemeType.HttpScheme="Bearer"
乔什·古斯特

20

使用ASP.Net Core 3.1,这对我有用:

services.AddSwaggerGen(s =>
        {
            s.SwaggerDoc("v1", new OpenApiInfo
            {
                Version = "v1",
                Title = "Chat API",
                Description = "Chat API Swagger Surface",
                Contact = new OpenApiContact
                {
                    Name = "João Victor Ignacio",
                    Email = "ignaciojvig@gmail.com",
                    Url = new Uri("https://www.linkedin.com/in/ignaciojv/")
                },
                License = new OpenApiLicense
                {
                    Name = "MIT",
                    Url = new Uri("https://github.com/ignaciojvig/ChatAPI/blob/master/LICENSE")
                }

            });

            s.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
            {
                Description = "JWT Authorization header using the Bearer scheme (Example: 'Bearer 12345abcdef')",
                Name = "Authorization",
                In = ParameterLocation.Header,
                Type = SecuritySchemeType.ApiKey,
                Scheme = "Bearer"
            });

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

        });

感谢您提供的代码段,您对我有很大帮助!
Mateo Velenik

工作对我来说太
Tulshi达斯

11

小费!

为了避免总是Bearer在Swagger(aka Swashbuckle)身份验证对话框上输入关键字,例如:"bearer xT1...",可以使用以下配置:

services.AddSwaggerGen(setup =>
{
    // Include 'SecurityScheme' to use JWT Authentication
    var jwtSecurityScheme = new OpenApiSecurityScheme
    {
        Scheme = "bearer",
        BearerFormat = "JWT",
        Name = "JWT Authentication",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.Http,
        Description = "Put **_ONLY_** your JWT Bearer token on textbox below!",

        Reference = new OpenApiReference
        {
            Id = JwtBearerDefaults.AuthenticationScheme,
            Type = ReferenceType.SecurityScheme
        }
    };

    setup.AddSecurityDefinition(jwtSecurityScheme.Reference.Id, jwtSecurityScheme);

    setup.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        { jwtSecurityScheme, Array.Empty<string>() }
    });

});

我们只能通过TypeOpenApiSecurityScheme类的属性更改为:

Type = SecuritySchemeType.**Http**

代替

Type = SecuritySchemeType.**ApiKey**

:)

像这样...

包装方式:

Swashbuckle.AspNetCore(5.6.3)
Swashbuckle.AspNetCore.SwaggerUI(5.6.3)

我正在使用.NET Core 3.1,希望对您有所帮助!


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.