使用授权头(承载者)设置 Swagger (ASP.NET 核心)

我有一个 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
}
},
191548 次浏览

首先,你可以使用 Swashbuckle.AspNetCore核心软件包来自动生成你的招摇定义(在2.3.0上测试)

安装包之后,将其安装到 ConfigureServices 方法的 Startup.cs 中

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


});

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

至少您可以尝试使用这个包来生成有效的 swagger 定义

目前,Swagger 具有使用 JWT 令牌进行身份验证的功能,并且可以自动将令牌添加到头文件中,我已经回答了 给你

不推荐使用 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);
});

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


});

小费!

为了避免总是在 Swagger (a.k.a 虚张声势) auth 对话框中写入关键字 Bearer,比如: "bearer xT1...",你可以在 Startup类中使用 ConfigureServices(...)方法下面的代码/配置:

using Microsoft.OpenApi.Models;
...




services.AddSwaggerGen(setup =>
{
// Include 'SecurityScheme' to use JWT Authentication
var jwtSecurityScheme = new OpenApiSecurityScheme
{
BearerFormat = "JWT",
Name = "JWT Authentication",
In = ParameterLocation.Header,
Type = SecuritySchemeType.Http,
Scheme = JwtBearerDefaults.AuthenticationScheme,
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>() }
});


});

我们只能通过将 OpenApiSecurityScheme类的 Type属性更改为:

Type = SecuritySchemeType.Http

取而代之

Type = SecuritySchemeType.ApiKey.

:)

Like this...

包装:

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

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

在虚张声势中不需要生成令牌分离和密钥。还有招摇过市的支持。下面的工作为我与 asp.net 核心3.1和 keycloack auth。

swagger.AddSecurityDefinition(JwtBearerDefaults.AuthenticationScheme, new OpenApiSecurityScheme
{
Type = SecuritySchemeType.OAuth2,
Flows = new OpenApiOAuthFlows
{
Implicit = new OpenApiOAuthFlow
{
AuthorizationUrl = new Uri("https://youauthsrv.com/auth/realms/your-realm/protocol/openid-connect/auth"),
}
},
In = ParameterLocation.Header,
Scheme = JwtBearerDefaults.AuthenticationScheme,
});


swagger.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = JwtBearerDefaults.AuthenticationScheme
}
},
new string[] {}
}
});

在配置中

app.UseSwaggerUI(c =>
{
c.OAuthClientId("clientname");
c.OAuthRealm("your-realm");
});