OAuth2 Authentication in OpenAPI Swagger ASP.NET Core

OAuth2 Authentication in Swagger OpenAPI ASPNET Core

Today in this article, we shall discuss, how to add OAuth2 Authentication in OpenAPI Swagger ASP.NET Core 3.1 or .NET 5-based API application.

Today in this article, we will cover below aspects,

As we discussed in our last articles recently released Swagger V3.0 (OpenAPI v3.0 document specifications) documentation has brought a lot of improvements which include a few breaking changes too.

These differences often come as surprises until you are already aware of those details.

So, Let’s get started,

Create ASP.NET Core API application

Please create ASP.NET Core 3.1 or .NET 5 applications.

oauth2 swagger example, swagger oauth2 example yaml, openapi oauth2 example, swagger oauth2 spring boot, swagger oauth2-redirect url, swagger authentication example, swagger securitydefinitions, swagger authorization header,

Add Swashbuckle.AspNetCore NuGet package

Please add the below Nuget package to your WebAPI using a Command prompt or PMC(package manager console)

PM> Install-Package Swashbuckle.AspNetCore -Version 5.6.3

Note - Please use the latest version if available

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

  • Swashbuckle.AspNetCore.SwaggerUI
  • Swashbuckle.AspNetCore.Swagger
  • Swashbuckle.AspNetCore.SwaggerGen

Using AddSecurityDefinition and AddSecurityRequirements

Add below two methods to your swagger middleware below,

  • AddSecurityDefinition() and
  • AddSecurityRequirement()

Both above methods let you define your API security by defining one or more security schemes like OAuth2 or JWT or Basic authentication scheme.

services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "TheCodeBuzzService", Version = "v1" });
                c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                {
                    Type = SecuritySchemeType.OAuth2,
                    Flows = new OpenApiOAuthFlows
                    {
                        Implicit = new OpenApiOAuthFlow
                        {
                            AuthorizationUrl = new Uri("your-auth-url", UriKind.Relative),
                            Scopes = new Dictionary<string, string>
                            {
                                { "readAccess", "Access read operations" },
                                { "writeAccess", "Access write operations" }
                            }
                        }
                    }
                });
             });

Additionally please add OpenApiSecurityRequirement which lets you define the security scheme i.e OAuth2 that needs to be used.

OAuth2 Authentication in OpenAPI Swagger ASP.NET Core ,oauth2 swagger example, swagger oauth2 example yaml, openapi oauth2 example, swagger oauth2 spring boot, swagger oauth2-redirect url, swagger authentication example, swagger securitydefinitions, swagger authorization header,

Additionally, AddSecurityRequirement lets you enable the below schemes to Swagger (Open API) documentation which is discussed in the below articles in detail for your reference,

UseSwaggerUI in Configure() method

Please update UseSwaggerUI for using ClientId and secretes configuration as below,

       
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseSwagger();

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

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthentication();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

The generated swagger definition will look as below.

The ‘Authorize’ button will be displayed.

blank

Please click on the Authorize Button and provide OAuth2 credentials.

oauth2 swagger example, swagger oauth2 example yaml, openapi oauth2 example, swagger oauth2 spring boot, swagger oauth2-redirect url, swagger authentication example, swagger securitydefinitions, swagger authorization header,

That’s all, you are all set to use swagger with the OAuth2 authorization token.

The above OAuth2 scheme will be applied globally. OAuth2 scheme can be applied at the Operation level using Interface IOperationFilter.

Other references :

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!

Summary

In this post, we learned how to add OAuth2 Authentication to Swagger (OpenAPI) documentation in ASP.NET Core 3.1 or .NET 5 application. Swagger (OpenAPI) describes the standards and specifications for RESTFul API descriptions. Today we looked at enabling authentication schemes i.e OAuth2 scheme using the Swashbuckle tooling in the ASP.NET Core applications.



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.



7 thoughts on “OAuth2 Authentication in OpenAPI Swagger ASP.NET Core

  1. Nice article. I cannot get bearer token on ClientCredentials flow. When I track the Authorization header on filter, I get “bearer undefined”. Can you help me? [asp.net-core3.1]

    1. Hey Developer,

      Thanks for your feedback. There could be few possibilities for the issue. Please make sure to use the latest version swagger UI. Please make sure you are mapping the token format correctly(JSON format Mapping). Also, are you defining Oauth2 security schemes globally or at the Operation level?

  2. Thanks for the info. It’s very useful.

    #1: Is it possible to show the [CustomAuthorize(new[] { Role.SuperAdmin, Role.Admin, Role.User })] on Swagger UI? Where [CustomAuthorize] drives from [Authorize] with Swagger-OAS3, CORE 3.1 project.

    #2: In Swagger OAS3 used with Core 3.1, a lock image comes on endpoints even with no Authorization. How to hide the lock image only for specific action methods?

Leave a Reply

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