OperationFilter JWT Authorize Token in Swagger OpenAPI

OperationFilter Authorization header

In this post, we will see how to add JWT bearer authorization to Swagger/Open API documentation using OperationFilter.

If the scheme needs to be applied globally, we already looked at it in our previous article.

 Enable JWT swagger authorization in ASP.NET Core 

OpenAPI specification or Swagger 3.0 lets you define the different authentication types for an API like Basic authentication, OAuth, JWT bearer, etc.

As we discussed in our last article, recent releases on Swagger V3.0 documentation have brought a lot of improvements which include breaking changes too.

Today in this article we will also see some design changes while dealing with security schemes using OperationFilter.

If you have security schemes that you only want to apply to specific operations, then using IOpertionFilter makes it simple to configure.

IOperationFilter also lets you define multiple security schemes if needed.

Advantages of swagger specification in a nutshell,

  • These specifications are an attempt to create a universal description for REST API.
  • Swagger or OpenAPI describes standards and specifications for RESTFul API description.
  • This specification provides the advantage of understanding the RESTFul services easily (especially if developers are consuming any new Web API ) plus helps provide easy ready documentation and details of capabilities an organization owns.

Getting Started

Create ASP.NET Core 3.1 or 6 API

Please install below Nuget package below.

  PM> Install-Package Swashbuckle.AspNetCore -Version 5.0.1  

Note: Please use the latest available version

This single NuGet package shall add all other required components as shown below and you need not have to add them explicitly,

  • Swagger
  • SwaggerUI
  • SwaggerGen

Implement IOperationFilter interface

Operation filters can be implemented using the IOperationFilter interface.

We can retrieve API descriptions for relevant information like attributes, route information, etc. using this interface.

This Interface also lets you define and apply schemes to specific operations.

Create a class AuthOperationFilter derived from IOperationFilter.

Please override the method Apply (..). The following is the final implementation of class AuthOperationFilter.

public class AuthOperationFilter : IOperationFilter
    {
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {

            var authAttributes = context.MethodInfo
              .GetCustomAttributes(true)
              .OfType<AuthorizeAttribute>()
              .Distinct();

            if (authAttributes.Any())
            {

                operation.Responses.TryAdd("401", new OpenApiResponse { Description = "Unauthorized" });
                operation.Responses.TryAdd("403", new OpenApiResponse { Description = "Forbidden" });

                var jwtbearerScheme = new OpenApiSecurityScheme
                {
                    Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "bearerAuth" }
                };

                operation.Security = new List<OpenApiSecurityRequirement>
                {
                    new OpenApiSecurityRequirement
                    {
                        [ jwtbearerScheme ] = new string [] { }
                    }
                };
            }
        }
    }

Let’s enable OperationFilter in the Swagger middleware using,

 c.OperationFilter<AuthOperationFilter>()

Please note that we have used c.OperationFilter() instead of c.AddSecurityRequirement().

AddSecurityRequirement () method lets you define global security scheme which gets applied all the API whereas OperationFilter() allows us to add a filter to only specific API

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddCors();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "TheCodeBuzz-Service", Version = "v1" });
                c.AddSecurityDefinition("bearerAuth", new OpenApiSecurityScheme
                {
                    Name = "Authorization",
                    Type = SecuritySchemeType.Http,
                    Scheme = "bearer",
                    BearerFormat = "JWT",
                    In = ParameterLocation.Header,
                    Description = "JWT Authorization header using the Bearer scheme.",
                });

                //////Add Operation Specific Authorization///////
                c.OperationFilter<AuthOperationFilter>();
                ////////////////////////////////////////////////

                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);

             
            });
      }

Our WebAPI has two GET methods and only one is secured with the [Authorize] attribute.

Let’s execute the swagger and check the documentation generated,

Please click on the lock icon and enter the bearer value as shown below,

Successful 200(OK)

For a valid JWT token, you shall get a successful (200) OK response.

blank

Please make sure you get an UnAuthorized(401) response while using any invalid JWT token.

Other References:

If interested, you can generate a valid JWT-secured token programmatically by following the below article,

Enabling JWT Swagger authentication (Global)

Please refer to the below article,

Summary

In this post, we learned how to add JWT bearer authorization to swagger documentation using OperationFilter. We understood the recent updates to Swagger security implementation and learned how to apply any security schemes to specific operations using IOperationFilter.



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



6 thoughts on “OperationFilter – JWT Authorize Token in Swagger OpenAPI

  1. The API I am documenting has a lot of scopes available. In Swagger I wants to display each endpoint is providing what scopes authorize for it in .net core.

    1. Hi Priyanka,
      If I understood your question correctly, Operation filter interface already lets you control adding the scope per methods basis as per requirement. You need to identify such methods and add the required scopes.
      Apart from that you can use description or groupping mechanism to show to the user about authorization scope that needs to be used.
      Hope it helps.

  2. In operations filter you may add

    && !context.MethodInfo.GetCustomAttributes(true).OfType().Any();

    to isAuthorized condition in order to exclude AllowAnonymous decorated methods

Leave a Reply

Your email address will not be published. Required fields are marked *