添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
斯文的跑步机  ·  庐阳教育体育信息网·  2 月前    · 
会开车的山楂  ·  Nordson Electronics ...·  5 月前    · 
被表白的围巾  ·  QScrollArea with a ...·  8 月前    · 
唠叨的豆芽  ·  Tailwind Play·  1 年前    · 

Just over a year ago I blogged a simple way to add an authorization header to your swagger-ui with Swashbuckle . Although that works, Swagger-UI and Swashbuckle support a better way, which I’ll describe below.

Before starting I assume you’ve already got OAuth2 setup correctly on your application (using bearer tokens), and you have decorated your controllers and actions with [Authorize] attributes. If you haven’t, that is beyond the scope of this blog post. Here all I’m doing is explaining how to configure Swashbuckle.

First, you need to tell Swashbuckle what security your API has:

services.AddSwaggerGen(options => options.AddSecurityDefinition("oauth2", new ApiKeyScheme Description = "Standard Authorization header using the Bearer scheme. Example: \"bearer {token}\"", In = "header", Name = "Authorization", Type = "apiKey"

This adds a securityDefinition to the bottom of the Swagger document, which Swagger-UI renders as an “Authorize” button:

Clicking that brings up a dialog box where you can put your bearer token:

The next thing we need to do is tell Swashbuckle which of our actions require Authorization. To do that you can use the SecurityRequirementsOperationFilter:

services.AddSwaggerGen(options => options.AddSecurityDefinition("oauth2", new ApiKeyScheme Description = "Standard Authorization header using the Bearer scheme. Example: \"bearer {token}\"", In = "header", Name = "Authorization", Type = "apiKey" options.OperationFilter<SecurityRequirementsOperationFilter>();

You can either download the SecurityRequirementsOperationFilter from here , or, if you’re using ASP.NET Core you can install my Swashbuckle.AspNetCore.Filters package from NuGet, which includes it (and other filters).

The SecurityRequirementsOperationFilter adds a security property to each operation in the Swagger document, which renders in Swagger-UI as a padlock next to the operation:

Once you’ve done that, when you “Try it out” using the Swagger-UI, the authorization header with your bearer token should be sent to your API.