当前位置:首页 > Web开发 > 正文

Add JWT Bearer Authorization to Swagger and ASP.NET Core

2024-03-31 Web开发

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:

 

dotnet add package swashbuckle.aspnetcore

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.

using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using Swashbuckle.AspNetCore.Swagger; namespace JwtSwaggerDemo.Infrastructure { public static class SwaggerServiceExtensions { public static IServiceCollection AddSwaggerDocumentation(this IServiceCollection services) { services.AddSwaggerGen(c => { c.SwaggerDoc("v1.0", new Info { Title = "Main API v1.0", Version = "v1.0" }); c.AddSecurityDefinition("Bearer", new ApiKeyScheme { Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"", Name = "Authorization", In = "header", Type = "apiKey" }); }); return services; } public static IApplicationBuilder UseSwaggerDocumentation(this IApplicationBuilder app) { app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1.0/swagger.json", "Versioned API v1.0"); c.DocExpansion("none"); }); return 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:

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/42120.html