引入swagger后,在services.AddSwaggerGen
中增加如下内容
// Register the Swagger generator, defining 1 or more Swagger documents
services.AddSwaggerGen(c =>
{
......
//Bearer 的scheme定义
var securityScheme = new OpenApiSecurityScheme()
{
Description = "JWT Authorization header using the Bearer scheme. Example: "Authorization: Bearer {token}"",
Name = "Authorization",
//参数添加在头部
In = ParameterLocation.Header,
//使用Authorize头部
Type = SecuritySchemeType.Http,
//内容为以 bearer开头
Scheme = "bearer",
BearerFormat = "JWT"
};
//把所有方法配置为增加bearer头部信息
var securityRequirement = new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "bearerAuth"
}
},
new string[] {}
}
};
//注册到swagger中
c.AddSecurityDefinition("bearerAuth", securityScheme);
c.AddSecurityRequirement(securityRequirement);
});
添加成功后,swagger右上方会有一个Authroize
按钮,点击后可以输入bearer token。
每个API方法后,会有一个锁的标志,表明该方法会传递bearer token。