Add an authorization header to your swagger-ui with Swashbuckle (revisited)

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s