使用授权标头 (Bearer) 设置 Swagger (ASP.NET Core)
Posted
技术标签:
【中文标题】使用授权标头 (Bearer) 设置 Swagger (ASP.NET Core)【英文标题】:Setting up Swagger (ASP.NET Core) using the Authorization headers (Bearer) 【发布时间】:2017-09-12 20:20:17 【问题描述】:我有一个 Web API (ASP.NET Core),我正在尝试调整 swagger 以从中进行调用。 调用必须包含 Authorization 标头,并且我正在使用 Bearer 身份验证。 来自 Postman 等第三方应用程序的呼叫运行良好。 但是我在为 swagger 设置标题时遇到了问题(由于某种原因,我没有收到标题)。这就是现在的样子:
"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
,
【问题讨论】:
我用 firebase ***.com/questions/61540706/… 【参考方案1】: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);
);
【讨论】:
可以确认这对 .NET Core 3.0 来说就像一个魅力 - 我在使用 .NET Core 2.2 时编写的代码在升级后不再有效,而这正是我所需要的 次要问题:i) 我需要使用 而不是 \r\n 才能正确显示消息。 ii) 而不是 new Info ... 我需要 new OpenApiInfo Title ... 。 [使用 swashbuckle.aspnetcore 5.0.0 和 Microsoft.OpenApi 1.1.4 [.net core 3.1]] 怎么样:1. AllowAnonymous 2. Roles? 这对我有用,但描述“\r\n”部分不起作用... @Ben 它被转换成 HTML,所以你可以使用 而不是 "\r\n"【参考方案2】:首先,您可以使用Swashbuckle.AspNetCore
nuget 包来自动生成您的招摇定义。 (在 2.3.0 上测试)
安装包后,在 Startup.cs 的 ConfigureServices 方法中设置它
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定义
【讨论】:
很好的答案,但是当我使用 ABP 样板进行此操作时,它不适用于 Dynamic Web Api (aspnetboilerplate.com/Pages/Documents/Dynamic-Web-API) @VadimK 在我升级到 .NET Core 2.0 之前效果很好 如果这有帮助,在 Auth 框中,在值输入中,您必须准确放置 Auth 标头,而不仅仅是 JWT(如果您正在使用它)。这意味着:承载 your_token_jwt 确保在令牌前加上“Bearer”。我没有使用 Bearer your_token_jwt 他们做了什么:1. AllowAnonymous 2. Roles?【参考方案3】:提示!
为了避免总是在 Swagger(aka Swashbuckle) 身份验证对话框上写关键字 Bearer
,例如:"bearer xT1..."
,您可以在 ConfigureServices(...)
方法上使用下面的代码/配置 Startup
类:
using Microsoft.OpenApi.Models;
...
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>()
);
);
我们可以做到这一点,只需将OpenApiSecurityScheme
类的Type
属性更改为:
Type = SecuritySchemeType.**Http**
改为
Type = SecuritySchemeType.**ApiKey**
.
包:
Swashbuckle.AspNetCore(5.6.3)
Swashbuckle.AspNetCore.SwaggerUI(5.6.3)
我正在使用 .NET Core 3.1,希望对您有所帮助!
【讨论】:
非常感谢您发布提示。我一直在寻找一种避免在招摇中输入 Bearer 的方法,这很有帮助。 谢谢!这对我有用并在 Swagger UI 中显示了授权按钮。 谢谢,工作。很好很容易【参考方案4】:使用 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>()
);
);
【讨论】:
谢谢你的代码 sn-p,你帮了我很多!【参考方案5】:无需单独生成token并在swagger中键入。 Swagger 也支持生成部分。下面使用 asp.net core 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");
);
【讨论】:
【参考方案6】:目前 Swagger 具有使用 JWT-token 进行身份验证的功能,并且可以自动将令牌添加到 header 中,我已回答 here。
【讨论】:
以上是关于使用授权标头 (Bearer) 设置 Swagger (ASP.NET Core)的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 nodejs 设置 Authorization Bearer 标头
Nuxt Apollo 模块请求授权标头,带有双 'Bearer'