Add JWT Bearer Authorization to Swagger and ASP.NET Core

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/

原文地址:https://www.cnblogs.com/frank0812/p/11963655.html

时间: 2024-08-28 03:26:02

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

Swagger 在asp.net core中的应用2

Swagger是一个把api和注释生成一个可视(或可访问)的输出工具,关且还可以进行手工测试我们的api,解决了程序不想写文档的问题(哈哈). Swashbuckle.AspNetCore是用来解决asp.net core下的api文档,不但能称显UI,还可以在UI上进行测试. 如果在asp.net core中使用swagger,首先在nuget下安装Swashbuckle.AspNetCore,不过现在是预览版,一定要把"包括预发行版"打上勾. 同时还要添加三个引用: Swashbu

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

asp.net core中使用Swashbuckle.AspNetCore生成接口文档 Swashbuckle.AspNetCore:swagger的asp.net core实现,本文使用版本为v1.1.0项目地址:https://github.com/domaindrivendev/Swashbuckle.AspNetCore仔细看了下readme,发现在百度找半天的东西其实readme里面就有... 开局一张图,然后开始编,一些基本的asp.net core东西就不再赘述,本文只对Swash

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

本文转自:http://www.cnblogs.com/rohelm/p/Authorization.html 本文目录 Asp.net Core 对于授权的改动很友好,非常的灵活,本文以MVC为主,当然如果说webapi或者其他的分布式解决方案授权,也容易就可以实现单点登录都非常的简单,可以使用现成的IdentityServer框架或者自定义实现动非常方便和干净,如果你在运行示例代码的时候未达到预期效果,请把文章拉到结尾寻找答案. 本文示例代码下载,github我这访问不了,暂且直接上传博客园

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

小分享:我有几张阿里云优惠券,用券购买或者升级阿里云相应产品最多可以优惠五折!领券地址:https://promotion.aliyun.com/ntms/act/ambassador/sharetouser.html?userCode=ohmepe03 在<管道是如何处理HTTP请求的?>中,我们对ASP.NET Core的请求处理管道的构成以及它对请求的处理流程进行了详细介绍,接下来我们需要了解的是这样一个管道是如何被构建起来的.这样一个管道由一个服务器和一个HttpApplication

Asp.Net Core webApi Swagger 配置说明

概要在官网上很容 可以找到开启Swagger Gen 的配置信息,这也是我们快速开发 Api 的开始使得我们不用写API 的文档和测试了 .理想很丰满,但在使用时我们 部分Get 接口可以用了但是我们Post 时候需要我们做 身份验证了,Token 是不错的选择.这也是.我学习Swagger ,不精的问题.怎么开启身份认证?. 进入正题 我把我用到的所有代码黏贴出来:一个个的说: Swagger 注册: services.AddSwaggerGen(c => { c.OperationFilte

asp.net core 2.0 web api基于JWT自定义策略授权

JWT(json web token)是一种基于json的身份验证机制,流程如下: 通过登录,来获取Token,再在之后每次请求的Header中追加Authorization为Token的凭据,服务端验证通过即可能获取想要访问的资源.关于JWT的技术,可参考网络上文章,这里不作详细说明, 这篇博文,主要说明在asp.net core 2.0中,基于jwt的web api的权限设置,即在asp.net core中怎么用JWT,再次就是不同用户或角色因为权限问题,即使援用Token,也不能访问不该访

ASP.NET Core 2.0利用Jwt实现授权认证

背景 在微服务架构下,一般都会按不同的业务或功能将整个系统切分成不同的独立子系统,再通过REST API或RPC进行通讯并相互调用,形成各个子系统之间的串联结构.在这里,我们将采用REST API的通讯方式.比如: 1.有一个“用户中心”独立子系统名为“Lezhima.UserHub”,是一个基于ASP.NET Core mvc 2.0的项目. 2.有一个处理用户订单的独立子系统名为“Lezhima.UserOrder”,是一个基于ASP.NET Core webp api 2.0的项目. 3.

ASP.NET Core Web Api之JWT刷新Token(三)

原文:ASP.NET Core Web Api之JWT刷新Token(三) 前言 如题,本节我们进入JWT最后一节内容,JWT本质上就是从身份认证服务器获取访问令牌,继而对于用户后续可访问受保护资源,但是关键问题是:访问令牌的生命周期到底设置成多久呢?见过一些使用JWT的童鞋会将JWT过期时间设置成很长,有的几个小时,有的一天,有的甚至一个月,这么做当然存在问题,如果被恶意获得访问令牌,那么可在整个生命周期中使用访问令牌,也就是说存在冒充用户身份,此时身份认证服务器当然也就是始终信任该冒牌访问令

ASP.NET Core 使用 JWT 自定义角色/策略授权需要实现的接口

目录 ① 存储角色/用户所能访问的 API ② 实现 IAuthorizationRequirement 接口 ③ 实现 TokenValidationParameters ④ 生成 Token ⑤ 实现服务注入和身份认证配置 ⑥ 实现登陆 ⑦ 添加 API 授权策略 ⑧ 实现自定义授权校验 ⑨ 一些有用的代码 ① 存储角色/用户所能访问的 API 例如 使用 List<ApiPermission>存储角色的授权 API 列表. 可有可无. 可以把授权访问的 API 存放到 Token 中,T