Swagger中添加Token验证
Swagger中添加Token验证
平常做项目使用mvc+webapi,采取前后端分离的方式,后台提供API接口给前端开发人员。这个过程中遇到一个问题后台开发人员怎么提供接口说明文档给前端开发人员。为了解决这个问题,项目中引用swagger(我比较喜欢戏称为“丝袜哥”)。
列出所有API控制器和控制器描述
那么既然是api,肯定涉及到安全验证问题,那么怎么在测试文档增加添加Token安全验证呢;
下面我们来看看
1、定义swagger请求头
using Microsoft.AspNetCore.Authorization;using Swashbuckle.AspNetCore.Swagger;using Swashbuckle.AspNetCore.SwaggerGen;using System.Collections.Generic;using System.Linq;using System.Reflection;
namespace CompanyName.ProjectName.HttpApi.Host.Code{/// /// swagger请求头/// public class HttpHeaderOperationFilter : IOperationFilter{/// // /// /// public void Apply(Operation operation, OperationFilterContext context){#region 新方法
if (operation.Parameters == null){operation.Parameters = new List();}
if (context.ApiDescription.TryGetMethodInfo(out MethodInfo methodInfo)){if (methodInfo.CustomAttributes.All(t => t.AttributeType != typeof(AllowAnonymousAttribute))&& !(methodInfo.ReflectedType.CustomAttributes.Any(t => t.AttributeType == typeof(AuthorizeAttribute)))){operation.Parameters.Add(new NonBodyParameter{Name = "Authorization",In = "header",Type = "string",Required = true,Description = "请输入Token,格式为bearer XXX"});}}
#endregion 新方法}}}
2、在ConfigureServices方法添加OperationFilter
/// // /// // This method gets called by the runtime. Use this method to add services to the container.public IServiceProvider ConfigureServices(IServiceCollection services){services.Replace(ServiceDescriptor.Transient());services.AddMvc().AddJsonOptions(options =>{options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;options.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.IsoDateTimeConverter(){DateTimeFormat = "yyyy-MM-dd HH:mm:ss"});//小写options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();options.SerializerSettings.ContractResolver = new DefaultContractResolver();// // options.SerializerSettings.DateFormatString = "yyyy-MM-dd";});// services.AddMvc().AddXmlSerializerFormatters();// services.AddMvc().AddXmlDataContractSerializerFormatters();services.AddLogging();services.AddCors(options =>options.AddPolicy("AllowSameDomain", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()));services.Configure(options =>{options.Filters.Add(new CorsAuthorizationFilterFactory("AllowSameDomain"));});
#region Swagger
services.AddSwaggerGen(c =>{c.SwaggerDoc("v1", new Info{Version = "v1",Title = "接口文档",Description = "接口文档-基础",TermsOfService = "https://example.com/terms",Contact = new Contact{Name = "XXX1111",Email = "[email protected]",Url = "https://example.com/terms"},License = new License{Name = "Use under LICX",Url = "https://example.com/license",}});
c.SwaggerDoc("v2", new Info{Version = "v2",Title = "接口文档",Description = "接口文档-基础",TermsOfService = "https://example.com/terms",Contact = new Contact{Name = "XXX2222",Email = "[email protected]",Url = "https://example.com/terms"},License = new License{Name = "Use under LICX",Url = "https://example.com/license",}});c.OperationFilter();c.DocumentFilter();var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);c.IncludeXmlComments(xmlPath);c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"CompanyName.ProjectName.ICommonServer.xml"));});
#endregion Swagger
#region MiniProfiler
if (bool.Parse(Configuration["IsUseMiniProfiler"])){//https://www.cnblogs.com/lwqlun/p/10222505.htmlservices.AddMiniProfiler(options =>options.RouteBasePath = "/profiler").AddEntityFramework();}
#endregion MiniProfiler
services.AddDbContext(options => options.UseMySql(Configuration["Data:MyCat:ConnectionString"]));var container = AutofacExt.InitAutofac(services, Assembly.GetExecutingAssembly());return new AutofacServiceProvider(container);}
3、定义一个ActionFilterAttribute
using CompanyName.ProjectName.Core;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Filters;using Newtonsoft.Json;using System.Security.Principal;
namespace CompanyName.ProjectName.HttpApi.Host{/// /// 权限/// public class BasicAuth : ActionFilterAttribute{/// // /// public override void OnActionExecuting(ActionExecutingContext context){if (context.HttpContext.Request != null && context.HttpContext.Request.Headers != null && context.HttpContext.Request.Headers["Authorization"].Count > 0){var token = context.HttpContext.Request.Headers["Authorization"];if (string.IsNullOrWhiteSpace(token)){ResultDto meta = ResultDto.Err("Unauthorized");JsonResult json = new JsonResult(new{Meta = meta});JsonSerializerSettings jsetting = new JsonSerializerSettings();jsetting.NullValueHandling = NullValueHandling.Ignore;jsetting.Converters.Add(new Newtonsoft.Json.Converters.IsoDateTimeConverter(){DateTimeFormat = "yyyy-MM-dd HH:mm:ss"});json.SerializerSettings = jsetting;json.ContentType = "application/json; charset=utf-8";context.Result = json;}else{GenericIdentity ci = new GenericIdentity(token);ci.Label = "conan1111111";context.HttpContext.User = new GenericPrincipal(ci, null);}}else{ResultDto meta = ResultDto.Err("Unauthorized");JsonResult json = new JsonResult(new{Meta = meta});JsonSerializerSettings jsetting = new JsonSerializerSettings();jsetting.NullValueHandling = NullValueHandling.Ignore;jsetting.Converters.Add(new Newtonsoft.Json.Converters.IsoDateTimeConverter(){DateTimeFormat = "yyyy-MM-dd HH:mm:ss"});json.SerializerSettings = jsetting;json.ContentType = "application/json; charset=utf-8";context.Result = json;}base.OnActionExecuting(context);}}}
4、最后在需要的地方使用 [BasicAuth]
/// /// 添加/// /// /// 主键id[BasicAuth][ModelValidationAttribute][ApiExplorerSettings(GroupName = "v1")][HttpPost, Route("Create")]public async Task> CreateAsync([FromBody]CreateWebConfigDto model){return await _webConfigApp.CreateAsync(model, new Core.CurrentUser());}
我们就可以看到Authorization - 请输入Token,格式为bearer XXX
源码地址:
https://github.com/conanl5566/Sampleproject/tree/master/src/03%20Host/CompanyName.ProjectName.HttpApi.Host
Swagger中添加Token验证相关教程
Nexus添加的包怎么就下载不下来?
Nexus添加的包怎么就下载不下来? Nexus添加的包怎么就下载不下来? 最近在本地Nexus中添加了一个外部依赖包,通过Nexus后台可以查看,通过URL也可以访问,可是本地开发环境就是说找不到。 错误如下: [ERROR] Failed to execute goal on project enterprise-
宝塔lnmp环境 添加站点后提示 No input file specified.
宝塔lnmp环境 添加站点后提示 No input file specified. 宝塔lnmp环境 添加站点后提示 No input file specified. 解决方法: 修改 /www/server/nginx/conf/fastcgi.conf 文件 添加代码: fastcgi_param PHP_ADMIN_VALUE “open_basedir=/www/wwwroot/:/tmp/:/
windows运行对话框_如何在Windows运行对话框中添加文本快捷方式
windows运行对话框_如何在Windows运行对话框中添加文本快捷方式? windows运行对话框 Windows comes prepackaged with a ton of handy run-dialog shortcuts to help you launch apps and tools right from the run box; is it possible to add in your own c
debian 添加service服务
debian 添加service服务 为什么80%的码农都做不了架构师? fedora中添加service用的是chkconfig --add 网上的资料按照操作,成功率很高,在debian中 ,添加service用到的是update-rc.d按照网上的教程添加,虽然教程写的没有问题,但是在操作的时候还是碰到不
centos7 给未知屏幕添加分辨率
centos7 给未知屏幕添加分辨率 为什么80%的码农都做不了架构师? 我想在分辨率的选项中添加一个1280x960选项 1.首先利用 cvt 新建一个 modeline cvt 1280 960 60 1280为宽 960为高 60为刷新频率(kHz) 2.屏幕上会返回两行内容,赋值第二行中 ‘Modeline’ 后
如何阻止人们将您添加到iPhone和Android上的WhatsApp组
如何阻止人们将您添加到iPhone和Android上的WhatsApp组 ( Control WhatsApp Group Invites on Android ) Using a new privacy setting on Android, you can now stop everyone, or just people not in your contact book, from adding you to WhatsApp group
discuz论坛添加水印
discuz论坛添加水印 discuz论坛后台是支持水印功能的,而添加水印功能需要GD库的支持,我原先的gd库是如下图所示,但是水印效果显示不出来;找了一些网上的资料,gd库支持的不全面,于是重新做修改: 进入到gd库下 #./configure --with-jpeg-dir --with-png-
将code添加到上下文菜单_创建上下文菜单项以将文本文件复制到Win
将code添加到上下文菜单_创建上下文菜单项以将文本文件复制到Windows 7 / Vista / XP中的剪贴板... 将code添加到上下文菜单 If you are the type of person that likes to keep a lot of information stored in text-format files on your drive, you’ve pr