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 = "XXX1111@qq.com", 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 = "XXX2222@qq.com", 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.html services.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
token验证_Swagger中添加Token验证相关推荐
- php sawgger token验证,Swagger中添加Token验证
Swagger中添加Token验证 Swagger中添加Token验证 平常做项目使用mvc+webapi,采取前后端分离的方式,后台提供API接口给前端开发人员.这个过程中遇到一个问题后台开发人员怎 ...
- axios请求中添加token,Authorization中添加token
axios({method: 'get',url: url,responseType: 'blob',headers: { 'Authorization': 'Bearer ' + getToken( ...
- Vue:全局拦截所有请求,并在请求头中添加token
Vue:全局拦截所有请求,并在请求头中添加token 在实际的项目中,为了登录的安全,token是必不可少的,所以就需要前后端配合,后端生成和验证token(这方面我也写过博客,讲述后端对token的 ...
- 深度学习实战(4)如何向BERT词汇表中添加token,新增特殊占位符
向BERT词汇表中添加token 问题表述 添加特殊占位符号 add_special_tokens 其他占位符接口 报错与解决方案 问题表述 在实际应用或者学术科研过程中,我们常常需要添加一些特殊的占 ...
- 如何在网站中添加验证码验证
要在网站中添加验证码验证,可以按照以下步骤进行操作: 在HTML表单中添加验证码输入框.在表单中添加一个输入框,用于让用户输入验证码. 生成随机验证码并保存到会话中.在服务器端生成一个随机的验证码,并 ...
- postman登录获取token,接口header中添加token发送请求
[Postman]登录获取token,接口header中添加token发送请求 说明 开始 说明 该文章只是用于记录,防止自己忘记. 开始 1.准备登录接口 2.添加全局变量 3.添加一个登录接口,登 ...
- Swagger在header中添加token
概述 平常做项目使用mvc+webapi,采取前后端分离的方式,后台提供API接口给前端开发人员.这个过程中遇到一个问题后台开发人员怎么提供接口说明文档给前端开发人员.为了解决这个问题,项目中引用sw ...
- axios请求拦截器在请求头中添加token
验证用户是否需要登陆,如果需要登陆在请求前在请求头中自动添加token字段. 代码: // request 拦截器 // 可以自请求发送前对请求做一些处理 request.interceptors.r ...
- ajax被token拦截,vue中封装ajax请求,并且拦截请求在请求头中添加token
/** * 封装请求方法 * @param {Object} url 接口请求地址 * @param {Object} data 接口请求参数(无需请求方式参数,则此项可以为空,否则必须传) * @p ...
最新文章
- 智能物联网(AIoT,2020年)(上)
- 013_CSS兄弟选择器
- 【BZOJ】1031: [JSOI2007]字符加密Cipher(后缀数组)
- SQL Server 分布式数据库的问题和解决方法
- 汽车电子专业知识篇(四)-一文详解无人驾驶中的各种感知传感器
- VMvare桥接网络连接不上解决办法
- 内核调试神器SystemTap — 探测点与语法(二)
- Linux shell__文件操作
- JZOJ1286太空电梯
- TCP/IP---ping命令
- (一)PC 机与单片机通信(RS232 协议)【800个电子设计大赛资料合集】
- 路由器k2固件改系统时间
- 透视投影的原理和实现
- POJ 3233 矩阵快速幂
- Python3入门教程:Excel 基础操作(上)
- IComponent2 Interface 学习
- 分享50个漂亮的设计师个人作品集网站案例
- IBus Pinyin 导入Sougou词库
- FishC《零基础学习python》笔记--第007、008讲、009讲:了不起的分支和循环1、2、3
- cad如何批量转换成pdf?
热门文章
- IIS 7.5 配置伪静态方法
- 工作中常用到的Linux命令
- python day-15 匿名函数 sorted ()函数 filter()函数 map()函数 递归 二分法...
- Linear Algebra lecture6 note
- java 10-4 Scanner方法
- Reactjs相比较原生方案是绝对的快吗?哪些情况下React有优势
- Theano2.1.1-基础知识之准备工作
- php关闭warning
- 21 week4 submit buidAndRun() node-rest-client
- php实现 明明的随机数