使用授权标头 (Bearer) 设置 Swagger (ASP.NET Core) [英] Setting up Swagger (ASP.NET Core) using the Authorization headers (Bearer)
本文介绍了使用授权标头 (Bearer) 设置 Swagger (ASP.NET Core)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 Web API (ASP.NET Core),我正在尝试调整 swagger 以从它进行调用.调用必须包含 Authorization 标头,并且我正在使用 Bearer 身份验证.来自 Postman 等第三方应用程序的调用正常.但是我在为 swagger 设置标题时遇到了问题(由于某种原因,我没有收到标题).这是现在的样子:
I have a Web API (ASP.NET Core) and I am trying to adjust the swagger to make the calls from it. The calls must contains the Authorization header and I am using Bearer authentication. The calls from third party apps like Postman, etc. go fine. But I am having the issue with setting up the headers for swagger (for some reason I don't receive the headers). This is how it looks like now:
"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
}
},
推荐答案
ApiKeyScheme 已弃用,在版本 5 中您可以这样使用:
ApiKeyScheme was deprecated, in version 5 you can use like this:
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.
Enter 'Bearer' [space] and then your token in the text input below.
Example: '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);
});
这篇关于使用授权标头 (Bearer) 设置 Swagger (ASP.NET Core)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文