NetCore3.1 如何添加带有JWT Token 验证的Swagger
发布日期: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(); }); } }}
View Code

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();        }    }}
View Code

5、修改Swagger输出文件,请参考启动类中的XML名称,如下:

 

 右键您的项目,选择:‘生成’

 

 然后设置为:

 

 6、设置启动项,如下:

 

 找到这个Json文件,修改如下:

"profiles": {    "IIS Express": {      "commandName": "IISExpress",      "launchBrowser": true,      "launchUrl": "swagger/index.html",      "environmentVariables": {        "ASPNETCORE_ENVIRONMENT": "Development"      }    }

 

 

 这样,您的Swagger就会有授权的小图标了。如下效果:

 

 这样就完成了,如果您觉得不错,就点个赞吧。

@天才卧龙的博客

上一篇:高并发时,使用Redis应注意的问题【缓存穿透、缓存击穿.、缓存雪崩】
下一篇:NetCore获取当前请求URL的方法

发表评论

最新留言

能坚持,总会有不一样的收获!
[***.219.124.196]2025年04月30日 07时31分40秒