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

31 thoughts on “Add an authorization header to your swagger-ui with Swashbuckle (revisited)

  1. I am getting “Fetch error Internal Server Error v1/swagger.json” after adding options.OperationFilter(); Is there anything special that needs to be added anywhere else in the application? Do you perhaps have a working example project?

  2. In my case , I need to store the bearer token returned after authenication(oAuth) and then pass on the same for further requests from Swagger UI. Any Ideas on how to store and process the bearer token, I have already followed all steps mentioned on your blog post

    • I don’t understand your question, sorry.

      Where does the bearer token come from? Normally in web apis the bearer token will come from an external identity system.

      Where do you want to store the bearer token? In swagger-ui somewhere? The swagger-ui javascript can be customised via Swashbuckle, but I’m not sure if that will help you.

  3. Hello Matt,

    I end up on your post while looking for a solution to what I’m trying to sort out which I believe it’s similar but not precisely the same:
    On my back end, I haven’t implemented or used OAuth2. It’s not what I’m interested into right now but I want to make my clients send a key to the back-end as a sort of security mechanism. It’s still in development phase.
    I just need to be able to send a key-value pair on the headers with the Swagger interface, as I would do it with Postman for instance. How can I achieve this?

  4. Thanks a lot for your help. Now, it works perfectly fine :)

    Yes, I’m developing on ASP.NET Core. I have a very simple Middleware that now is able to check that a Key is being sent. In the future, I might add OAuth2 but for the current phase, this is just fine.

  5. Hi, great article!!!
    Do you know how can I get the token first? On my web api I need to acces http://mysite/token passing username, password and grant_type. Then I receive the token, and this token should be passed in all requests. Is there a way to do that?
    Thankz!

  6. I am trying to do this, but in asp.net (full framework, not core), and I just don’t find any of the above code. Are there any examples in non .net core on how to do this as well?

    Cheers!

  7. I’ve been trying to get this to work for 2 days now. I cannot get “BASIC” authentication working. We want to use “BASIC” when doing testing integration. Any ideas why BASIC won’t work?

    • Basic authentication is different, and you probably won’t need my library to do it.

      Try this
      services.AddSwaggerGen(c =>
      {
      c.AddSecurityDefinition(“basic”, new ApiKeyScheme
      {
      Description = “Basic Authorization using username and password”,
      Type = “basic”
      });

      c.AddSecurityRequirement(new Dictionary<string, IEnumerable>
      {
      { “basic”, Enumerable.Empty() }
      });

      • No, that doesn’t work either. It seems as if Swagger just doesn’t work with authentication at all? I am using AspNetCore 2.2 project.

        This didn’t work either:
        c.OperationFilter();
        c.AddSecurityDefinition(“BASIC”, new BasicAuthScheme() { Type = “BASIC” });
        c.OperationFilter();

      • c.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();
        c.AddSecurityDefinition(“BASIC”, new BasicAuthScheme() { Type = “BASIC” });
        c.OperationFilter<SecurityRequirementsOperationFilter>();

      • @Tim I can’t help you I’m sorry. The code snippet I posted for you above works for me, we are using basic auth at work so I copied it from a working solution.

        All swagger does is document what your API does, it does not do the basic authentication for you (if that’s what you’re thinking). Here at work we are using the Bazinga.AspNetCore.Authentication.Basic NuGet package to do the basic authentication.

      • Hi Matt, no problem. I find it odd that BASIC auth works fine for me from Postman, just not Swagger. I can see through Fiddler that none of the auth headers are being sent back, but other headers are (ex. pageSize, pageNumber, etc.) for some methods. May I ask what else you’ve enabled besides just the standard auth pipelines (ex. services.AddAuthentication(…), app.UseAuthentication(), etc.)?

  8. Tim – I have a whole bunch of other stuff enabled but the code I posted above is all that you should need for basic auth. Do you see a padlock next to your actions as per the screenshots in my blog post? When you click the padlock, do you get a username and password prompt?

    • I finally figured it out. It dawned on me that the “app.UseAuthorization” was being called AFTER enabling swagger, this needed to be before it.

      : Configure :
      app.UseHttpsRedirection();
      this.ConfigureAuthentication(app, env);
      this.ConfigureSwagger(app, env);
      app.UseMvc();

  9. @mattfrear
    Great article.
    I have been trying to find a solution to the final piece of the puzzle. I have an Authorization Button in the header with a password flow for oAuth2. If I fill in and submit I get my oAuth2 token back from the server.

    I have decorated my operations with the [Authorize] attribute rather than SecurityRequirementsOperationFilter partly as I want to get just one working for now.

    The issue which remains is – even after you authorize, the Authorization: {token} header is not being attacked.

    What do you think that might be?

  10. Excellent article, thanks.
    Worth mentioning a problem I came across when I’ve implemented your code, I’ve received this error when I tried loading swagger:
    Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
    An unhandled exception has occurred while executing the request.
    System.ArgumentException: An item with the same key has already been added. Key: 401
    at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior)
    at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
    at Swashbuckle.AspNetCore.Filters.SecurityRequirementsOperationFilter`1.Apply(Operation operation, OperationFilterContext context)
    at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.CreateOperation(ApiDescription apiDescription, ISchemaRegistry schemaRegistry)
    at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.CreatePathItem(IEnumerable`1 ntext)

    The problem is SecurityRequirementsOperationFilter automatically adds 401 and 403 return values, which I added to the documentation manually. To avoid adding it twice, you should change

    options.OperationFilter();

    to

    options.OperationFilter(false);

    as described here:
    https://github.com/mattfrear/Swashbuckle.AspNetCore.Filters/blob/master/README.md#how-to-use—security-requirements-filter

    Thanks again.

  11. Very nicely written article. Works with Swagger, I got everything as expected. However, whenever I make a request to one of the methods marked with the Authorize attribute I get back status 500 and an exception that says “No authenticationScheme was specified, and there was no DefaultChallengeScheme found.” The method is not executing, of course. I could not figure out why this is happening. Any ideas?

    • Hi Marius. I don’t know sorry – what happens when you hit your API via Postman? Does it return the same error? If it does it’s probably a problem with your authentication setup rather than with Swashbuckle.

Leave a Reply to Rodrigo Souza Cancel 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