zoukankan      html  css  js  c++  java
  • NetCore3.1 如何添加带有JWT Token 验证的Swagger

    十年河东,十年河西,莫欺少年穷

    学无止境,精益求精

    大致分如下几步

    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<AddResponseHeadersFilter>();
                    c.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();
    
                    //在header中添加token,传递到后台
                    c.OperationFilter<SecurityRequirementsOperationFilter>();
                    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就会有授权的小图标了。如下效果:

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

    @天才卧龙的博客

  • 相关阅读:
    INSERT INTO插入行记录
    BULK INSERT导入数据库
    第三章 必须知道的一些基础知识[DDT书本学习 小甲鱼]【3】
    第三章 必须知道的一些基础知识[DDT书本学习 小甲鱼]【2】
    第二章 用Python设计第一个游戏[DDT书本学习 小甲鱼]
    第一章 就这么愉快地开始吧 [DDT书本学习 小甲鱼]
    Linux——添加用户操作
    Linux——常用命令
    Linux——ls
    redis基本命令
  • 原文地址:https://www.cnblogs.com/chenwolong/p/13405896.html
Copyright © 2011-2022 走看看