
NetCore3.1 如何添加带有JWT Token 验证的Swagger
View Code View Code
发布日期:2021-05-09 01:18:05
浏览次数:25
分类:精选文章
本文共 4752 字,大约阅读时间需要 15 分钟。
十年河东,十年河西,莫欺少年穷
学无止境,精益求精
大致分如下几步
1、安装Swagger包
Install-Package Swashbuckle.AspNetCore -Version 5.0.0
2、安装Swashbuckle.AspNetCore.Filters包 版本5.12
Install-Package Swashbuckle.AspNetCore.Filters -Version 5.1.2
3、修改启动类代码如下:
using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Threading.Tasks;using log4net;using log4net.Config;using log4net.Repository;using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Hosting;using Microsoft.AspNetCore.HttpsPolicy;using Microsoft.AspNetCore.Mvc;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Hosting;using Microsoft.Extensions.Logging;using Microsoft.OpenApi.Models;using Swashbuckle.AspNetCore.Filters;namespace LeyxStaffApi{ public class Startup { public static ILoggerRepository repository { get; set; } public Startup(IConfiguration configuration) { Configuration = configuration; // 指定配置文件 repository = LogManager.CreateRepository("NETCoreRepository"); XmlConfigurator.Configure(repository, new FileInfo("Log4Net.config")); //注册Swagger } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); #region 注册Swagger服务 // 注册Swagger服务 services.AddSwaggerGen(c => { // 添加文档信息 c.SwaggerDoc("v1", new OpenApiInfo { Title = "学生端相关接口", Version = "V1" }); //c.SwaggerDoc("demo", new OpenApiInfo { Title = "示例接口", Version = "demo" }); c.DocInclusionPredicate((docName, apiDesc) => apiDesc.GroupName == docName.ToUpper()); var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);//获取应用程序所在目录(绝对,不受工作目录影响,建议采用此方法获取路径) var xmlPath = Path.Combine(basePath, "LeyxStaffApi.xml"); c.IncludeXmlComments(xmlPath); #region Jwt //开启权限小锁 c.OperationFilter(); c.OperationFilter (); //在header中添加token,传递到后台 c.OperationFilter (); c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme { Description = "JWT授权(数据将在请求头中进行传递)直接在下面框中输入Bearer {token}(注意两者之间是一个空格) \"", Name = "Authorization",//jwt默认的参数名称 In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中) Type = SecuritySchemeType.ApiKey }); #endregion }); #endregion } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } //允许跨域 app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()); // 启用Swagger中间件 app.UseSwagger(c => c.RouteTemplate = "swagger/{documentName}/swagger.json"); // 配置SwaggerUI app.UseSwaggerUI(c => { //c.SwaggerEndpoint($"/swagger/demo/swagger.json", "demo"); c.SwaggerEndpoint($"/swagger/v1/swagger.json", "V1"); }); app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } }}
4、添加你的控制器
using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNetCore.Authorization;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Mvc;namespace LeyxStaffApi.Controllers{ [Route("Api/V1/Manager")] [ApiExplorerSettings(GroupName = "V1")] public class ManagerController : ControllerBase { [HttpPost] [Authorize] [Route("GetSchoolInfo")] public IActionResult GetSchoolInfo() { return Ok(); } }}
5、修改Swagger输出文件,请参考启动类中的XML名称,如下:
右键您的项目,选择:‘生成’
然后设置为:
6、设置启动项,如下:
找到这个Json文件,修改如下:
"profiles": { "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, "launchUrl": "swagger/index.html", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } }
这样,您的Swagger就会有授权的小图标了。如下效果:
这样就完成了,如果您觉得不错,就点个赞吧。
@天才卧龙的博客
发表评论
最新留言
能坚持,总会有不一样的收获!
[***.219.124.196]2025年04月30日 07时31分40秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
leetcode380. Insert Delete GetRandom O(1)
2023-01-31
LeetCode502
2023-01-31
leetcode507
2023-01-31
Leetcode: Group Anagrams
2023-01-31
Leetcode: Spiral Matrix II
2023-01-31
LeetCode: String to Integer (atoi)
2023-01-31
Leetcode:454. 4Sum II
2023-01-31
LeetCode:Restore IP Addresses
2023-01-31
LeetCode——Unique Paths
2023-01-31
LeetCode二叉树从上至下路径问题总结(112.113.437.129)
2023-01-31
LeetCode哈希表+字符类的题目总结
2023-01-31
LeetCode地平线专场——第308场周赛题解
2023-01-31
LeetCode数据库题目汇总二(附答案)
2023-01-31
LeetCode新手指南:从零开始掌握算法挑战
2023-01-31
LeetCode智加科技专场——第207场周赛题解
2023-01-31
leetcode正则表达式匹配
2023-01-31