Nswag OAuth2 Authorization OpenAPI Documentation in ASP.NET Core

NSwag OAuth2 Authorization OpenAPI swagger

In this post, we will see how to enable NSwag OAuth2 Authorization OpenAPI swagger in ASP.NET Core.

OpenAPI describes the standards and specifications for the RESTFul API description.

These specifications are an attempt to create a universal and language-agnostic description for describing the REST API.

Today in this article, we will cover below aspects,

Benefits of Open API specification

The open specification provides the advantage of understanding the RESTFul services easily (especially if developers are consuming any new Web API ).

-Helps provide easy ready documentation saving time.

-It provides details of the capabilities the service owns.

-Serve the Swagger UI to browse and test the web API.

-Client-side SDK generation.

-Helps in API discovery.

In our last article on NSwag Swagger API documentation in ASP.NET Core, we learned about the basics of adding Documentation in ASP.NET Core API using NSwag.

NSwag allows you to specify different authentication schemes like JWT, APIKey, or OAuth2 as supported by your API and generates the required document by following Swagger 2.0 and OpenAPI 3.0 specifications.

Let’s continue from our previous article and extend it to NSwag authentication for OAuth2.

We already had added the below Nuget packages to the project,

Add NSwag Nuget package

PM> Install-Package NSwag.AspNetCore -Version 13.4.2

OR

Install it through Nuget Package Manager,

The above updated NuGet package adds services required for OpenAPI 3.0 generation and exposes various extension methods like,

  • AddOpenApiDocument

  • AddSwagger

  • AddSwaggerDocument

Nswag- OAuth2- Update ConfigureServices()

Here below please define the API ApiSecuritySchemeTyp as ApiKey with OAuth2 authorization,

services.AddOpenApiDocument(document =>
            {
                document.AddSecurity("bearer", Enumerable.Empty<string>(), new OpenApiSecurityScheme
                {
                    Type = OpenApiSecuritySchemeType.OAuth2,
                    Flow = OpenApiOAuth2Flow.Implicit,
                    Description = "TheCodeBuzz OAuth2 Service",
                    Flows = new OpenApiOAuthFlows()
                    {
                        Implicit = new OpenApiOAuthFlow()
                        {
                            Scopes = new Dictionary<string, string>
                          {
                            { "read", "Read access to protected resources" },
                            { "write", "Write access to protected resources" }
                          },
                            AuthorizationUrl = "https://localhost:44333/oauth2service/secure/authorize",
                            TokenUrl = "https://localhost:44333/oauth2service/secure/token"
                        },
                    }
                });

Here is the complete code,

NSwag OAuth2

Add OpenAPI UI in the API pipeline

Please add below the Application builder extension to add the Swagger UI interface in the API pipeline.

Nswag OAuth2

Nswag- OAuth2 – Authorize button on OpenAPI UI

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

Nswag OAuth2 NET 5

Please provide the client_Id value and click on Authorize.

NswagO Auth2 client Id

That’s all, you are all set to use NSwag with an OAuth2 authentication enabled.

Additionally, if you need to prompt the user for entering client id or secret id before accessing API documentation, then please update OAuth2ClientSettings as below,

NSwag OAuth2

This will prompt the user to enter the credentials,

Nswag Oauth2

This authentication will be used for all APIs in the service as it’s global in nature.

You can also add service details like License, version, or Contact details in the metadata which is discussed already in our previous article.

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 Open API documentation using NSwag tooling with OAuth2 authentications.

OpenAPI 3.0 describes the standards and specifications for RESTFul API descriptions and NSwag helps us to leverage those specifications by generating nice documentation.



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.



Leave a Reply

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