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:

namespace JwtSwaggerDemo
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
public IServiceProvider ConfigureServices(IServiceCollection services)
{
//... rest of services configuration
services.AddSwaggerDocumentation(); //...
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
//.... rest of app configuration
app.UseSwaggerDocumentation();
}
//.... rest of app configuration
}
}

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.

For swagger 2.x

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

 
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" }); // Swagger 2.+ support
var security = new Dictionary<string, IEnumerable<string>>
{
{"Bearer", new string[] { }},
}; c.AddSecurityDefinition("Bearer", new ApiKeyScheme
{
Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
Name = "Authorization",
In = "header",
Type = "apiKey"
});
c.AddSecurityRequirement(security);
}); 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.DocumentTitle = "Title Documentation";
c.DocExpansion(DocExpansion.None);
}); return app;
}
}
}

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

Add JWT Bearer Authorization to Swagger and ASP.NET Core的更多相关文章

  1. 使用JWT的ASP.NET CORE令牌身份验证和授权(无Cookie)——第1部分

    原文:使用JWT的ASP.NET CORE令牌身份验证和授权(无Cookie)--第1部分 原文链接:https://www.codeproject.com/Articles/5160941/ASP- ...

  2. asp.net core使用Swashbuckle.AspNetCore(swagger)生成接口文档

    asp.net core中使用Swashbuckle.AspNetCore(swagger)生成接口文档 Swashbuckle.AspNetCore:swagger的asp.net core实现 项 ...

  3. ASP.NET Core系列:JWT身份认证

    1. JWT概述 JSON Web Token(JWT)是目前流行的跨域身份验证解决方案. JWT的官网地址:https://jwt.io JWT的实现方式是将用户信息存储在客户端,服务端不进行保存. ...

  4. [转]教你实践ASP.NET Core Authorization

    本文转自:http://www.cnblogs.com/rohelm/p/Authorization.html 本文目录 Asp.net Core 对于授权的改动很友好,非常的灵活,本文以MVC为主, ...

  5. ASP.NET Core 2 学习笔记(十三)Swagger

    Swagger也算是行之有年的API文件生成器,只要在API上使用C#的<summary />文件注解标签,就可以产生精美的线上文件,并且对RESTful API有良好的支持.不仅支持生成 ...

  6. Asp.Net Core配置Swagger

    本文主要参考:Using Swagger with ASP.net Core 1.创建WebApi项目 本文使用ASP.Net Core Web API项目模板演示Swagger到使用,首先创建Web ...

  7. ASP.NET Core管道深度剖析(4):管道是如何建立起来的?

    在<管道是如何处理HTTP请求的?>中,我们对ASP.NET Core的请求处理管道的构成以及它对请求的处理流程进行了详细介绍,接下来我们需要了解的是这样一个管道是如何被构建起来的.这样一 ...

  8. Docker & ASP.NET Core (2):定制Docker镜像

    上一篇文章:把代码连接到容器 Dockerfile 在Docker的世界里,我们可以通过一个叫Dockerfile的文件来创建Docker镜像,随后可以运行容器. Dockerfile就是一个文本文件 ...

  9. Asp.net core中的依赖注入

    使用服务 在Asp.net core的Controller中,可以通过如下两种方式获取系统注入的服务: 构造函数 可以直接在构造函数中传入所依赖的服务,这是非常常见的DI注入方式. public Va ...

随机推荐

  1. Mybatis 并发执行导致cpu占满的问题

    最近线上服务经常 出现cpu达到100%的问题,发现都是执行oracle操作的方法就没有返回.经过排查,最后定位到cpu消耗在以下方法 System.Collections.Generic.Dicti ...

  2. linux运维、架构之路-Kubernetes集群部署

    一.kubernetes介绍        Kubernetes简称K8s,它是一个全新的基于容器技术的分布式架构领先方案.Kubernetes(k8s)是Google开源的容器集群管理系统(谷歌内部 ...

  3. Eclipse搭建Maven项目并上传SVN备份

    本文出自:http://www.cnblogs.com/2186009311CFF/p/7226127.html 背景:近段时间在学着Java,想着用Java做BS的项目.但是项目一遇到问题又要重做, ...

  4. 五年双十一:SLS数据管道发展之路

    日志服务SLS是一款飞天团队自研产品,服务云上云下3W+客户,并在阿里经济体中作为日志数据的基础设施,在过去几年中经历多次双十一.双十二.新春红包锤炼.在2019双十一中: 服务阿里经济体3W+ 应用 ...

  5. 转:HTML5 History API 详解

    从Ajax翻页的问题说起 请想象你正在看一个视频下面的评论,在翻到十几页的时候,你发现一个写得稍长,但非常有趣的评论.正当你想要停下滚轮细看的时候,手残按到了F5.然后,页面刷新了,评论又回到了第一页 ...

  6. HDU 4277 USACO ORZ(DFS暴搜+set去重)

    原题代号:HDU 4277 原题链接:http://acm.hdu.edu.cn/showproblem.php?pid=4277 原题描述: USACO ORZ Time Limit: 5000/1 ...

  7. 正则表达式小结,数据预处理中常用的shell命令

    数据预处理中,这部分命令非常有用. 不需要编写代码,直接通过shell脚本通常就能修改文件格式.有时候sed和awk联合几乎能实现所有功能. 管道命令 | 重定向命令>,2>,>&g ...

  8. 续上文,Unity3D面试ABC

    http://www.unitymanual.com/blog-3573-685.html 最先执行的方法是: 1.(激活时的初始化代码)Awake,2.Start.3.Update[FixUpdat ...

  9. 项目二、自定义文件上传函数(js函数)

    /** * 文件上传工具 v1.0 * @param file 要上传的文件 * @param url 要上传到的路径 * @param div 要显示的区域 */ function uploader ...

  10. fedora23然后创建workspace?或者说是panel面板?

    好像在fedora23中 无法再添加工作空间workspace. 系统会自动的在非空工作空间后面再生成一个空的工作空间. 而且 工作空间 好像不只 4个, 可以有很多个. panel面板好像也不能添加 ...