Use OAuth2 Authorization Token in swagger .NET Core

In this post, we will see how to Use OAuth2 Authorization Token in swagger .NET Core.

Swagger or OpenAPI describe standards and specifications for RESTFul API description.

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

Today in this article, we will cover below aspects,

In our last article JWT (JSON Web Token) bearer Authentication in .NET Core, we learned about how to use JWT bearer token for securing .NET Core API.

If interested, ASP.NET Core 3.1 or .NET 5.0 and above has brought new improvements for swagger using OpenAPI v3 specifications (with new breaking changes ), please see here for more details,

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

Adding swagger definition in .NET Core is simply a 2-3 steps process.

1. Create a API sample service

Please use >ASP.NET Core 2.2 or 3.1

Please add below the Swashbuckle NuGet package to your WebAPI using the Command prompt or package manager console.

Command: Install-Package Swashbuckle.AspNetCore

OR

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
blank

2. Update ConfigureServices() method

Add below line to ConfigureServices() method as shown below,

 
public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddSwaggerGen(
            {
                c.SwaggerDoc("v1", new Info { Title = "MyTestService", Version = "v1" });
            });
        }

3. Update Configure() method

Add below line to Configure() method as shown below,

app.UseSwagger();
app.UseSwaggerUI(
         {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyTestService");
          });

Let’s see swagger definition generated,

blank

Add OAuth2 Authorization to WebAPI

Please add AddSecurityDefinition() and AddSecurityRequirement() methods as discussed below in details.

AddSecurityDefinition

This method lets you define how your API is secured by defining one or more security schemes. It lets you enable the below schemes. (One can use multiple security schemes if needed.)

  • Basic Authentication using BasicAuthScheme
  • JWT Bearer token using ApiKeyScheme
  • OAuth2 authentication using OAuth2Scheme

In the example, I have used OAuth2Scheme. Token and other details are provided manually but can be obtained programmatically.

Usually, required input can be made available as an environment variable or through secret storage or could be made available through the DI using a configuration file or YML files.

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddOptions();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info { Title = "MyTestService", Version = "v1" });
                c.AddSecurityDefinition("oauth2", new OAuth2Scheme
                {
                    Type = "oauth2",
                    Flow = "implicit",
                    AuthorizationUrl = "http://your-auth-url-oauth/",
                    Scopes = new Dictionary<string, string>
                    {
                        { "readAccess", "Access read operations" },
                        { "writeAccess", "Access write operations" }
                    }
                });

                c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
                {
                        { "oauth2", new[] { "readAccess", "writeAccess" } }
                });
                
            });

        }

AddSecurityRequirement

These 2 method lets you control the given authentication scheme applied at either the Global level or Operation level.

  • Global Authentication scheme

In the above example, I have used a global authentication scheme by using, which means the OAuth2 scheme will be applied to all REST API within the service.

In AddSecurityRequirement() when applying schemes of type other than “oauth2”, the array of scopes MUST be empty. Please note that while using JWT Swagger authorization scheme we had used it as empty. For OAuth2 array scopes are defined as “readAccess” and “writeAccess”.

Scopes are used to grant access to data on behalf of the end user. Each API may declare one or more scopes.

  • Local Authentication scheme

This scheme will be applied at the Operation level. Operation-specific security can be added by using an Interface called IOperationFilter.

Please see Enable JWT authorization in Swagger at the Operation level article for understanding more on its usage.

Once you run the swagger route, the Authorize button will be visible in the swagger UI.

The Configure method looks as below,

        /// <summary>
        /// 
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "TestService");
                c.OAuthClientId("client-id");
                c.OAuthClientSecret("client-secret");
                c.OAuthRealm("client-realm");
                c.OAuthAppName("OAuth-app");
                c.OAuthUseBasicAuthenticationWithAccessCodeGrant();
            });

            app.UseAuthentication();
            app.UseHttpsRedirection();
            app.UseMvc();
        }

blank

Please provide bearer value and click on Authorize.

OAuth2 Authorization Token in swagger NET Core

That’s all, you are all set to use swagger with the OAuth2 authorization token. Once validated, the authorization can be used used for all API until its validity.

If you are looking to understand how to customize Swagger API documentation pro-grammatically especially enabling the operation level authentication scheme, I would recommend you to read the below few posts.

Summary

In this post, we learned how to add OAuth2 authorization to swagger documentation. Swagger or OpenAPI describe standards and specifications for RESTFul API description. Open API specifications let you define the different authentication schemes like BasicAuthScheme, ApiKeyScheme, and OAuth2Scheme easily using the Swashbuckle NuGet package.




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.



3 thoughts on “Use OAuth2 Authorization Token in swagger .NET Core

  1. Hi,
    How can i use same with UsePkceWithAuthorizationCodeGrant() and Authorization code flow instead of implicit.

    Also, can i modify the swagger ui-Authorize popup, such that lets say I want to make client_id field to show value as hidden (passowrd protected like : *******), how can I do that.

Leave a Reply

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