使用授权标头(Bearer)设置Swagger(ASP.NET Core)
我有一个Web API(ASP.NET核心),我正在尝试调整swagger来进行调用。 这些调用必须包含Authorization标头,我正在使用Bearer身份validation。 来自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 } },
首先,您可以使用Swashbuckle.AspNetCore
nuget包自动生成您的swagger定义。 (在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 JWT with Bearer into field", Name = "Authorization", Type = "apiKey" }); c.AddSecurityRequirement(new Dictionary> { { "Bearer", Enumerable.Empty () }, }); });
然后,您可以使用页面右上角的“授权”按钮。
至少你可以尝试使用这个包来生成有效的swagger定义
目前,Swagger具有使用JWT-token进行身份validation的function,并且可以自动将令牌添加到标头中,我在这里已经回答了 。
- 在ASP.NET 5中将Razor视图渲染为字符串
- 如何在Asp.Net 5中使用Entity Framework 6.x(MVC 6)
- 如何在asp.net核心中编写自定义actionResult
- error handling(将ex.Message发送到客户端)
- 在ASP.NET Core中使用DirectoryServices
- 如何在ASP.NET MVC 6中继续使用ModelState和RedirectToAction?
- ASP.NET 5 / MVC 6 Ajax将模型发布到控制器
- 将google idToken替换为本地openId令牌c#
- OpenIdConnectAuthenticationHandler:message.State为null或为空