Buscar contenidos

viernes, 8 de marzo de 2019

Add JWT Bearer Authorization to Swagger and ASP.NET Core


https://ppolyzos.com/2017/10/30/add-jwt-bearer-authorization-to-swagger-and-asp-net-core/

If you have an ASP.NET Core web application that already has JWT authorization, this guide will help you add JWT (JSON Web Token) support to the Swagger UI.

What is Swagger UI?

Swagger UI is a collection of HTML, Javascript and CSS assets that dynamically generates beautiful documentation from a Swagger-compliant API. You can learn more in https://swagger.io/ and in the project’s GitHub repository.

Setup Swagger UI in ASP.NET Core

In order to use Swagger UI in your ASP.NET Core project you need a NuGet package called Swashbuckle.AspNetCore. You can add it to your project either by command line:
or using the NuGet package manager in Visual Studio:
Then you need to add Swagger support toConfigureServices(IServiceCollection services) and toConfigure(IApplicationBuilder app, IHostingEnvironment env) in your application’s Startup.cs file. To do so, you need to create a SwaggerServiceExtensions class and add the necessary code to support Swagger in your app.

Changes in Startup.cs file

Using the above class, the only thing you need to do in your Startup.cs file is the following:

Authorize requests in Swagger UI

Now, when you load the Swagger’s UI address (e.g: https://localhost:44321/swagger/#/), you will see an Authorize button at the top. Clicking on it leads to a modal window, which allows you to authorize your app with a JWT token, by adding Bearer <your_token> in the value input field.
It is like logging in with a user and, therefore, all your next API calls will be using this token to authorize requests.

How it works

In the following video, you may see how to request a JWT token for a user and then use it to access authorized requests.

For swagger 2.x

To support JWT authentication in Swagger 2.x you need to update your code with the following snippet:

No hay comentarios:

Publicar un comentario