日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

token验证_Swagger中添加Token验证

發布時間:2025/4/16 编程问答 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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验证的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。

主站蜘蛛池模板: 成人久久一区 | 伊人3| 日本v片| 亚洲成熟丰满熟妇高潮xxxxx | 国产片91| 四虎婷婷 | 午夜黄色网 | 精品午夜一区二区三区 | 丰满大乳奶做爰ⅹxx视频 | 中文字幕第一页在线 | 国产又粗又猛又爽又黄的视频一 | 激情婷婷丁香 | yy1111111| 国产成人无码一区二区在线观看 | 国产精品第四页 | 九七久久| 黄视频在线免费 | 三级成人在线 | 国产精品国产三级国产普通话蜜臀 | 一区www| 青青草原在线免费 | 69堂精品| 亚洲熟妇一区 | 性淫影院 | 午夜不卡久久精品无码免费 | 96免费视频| 啪啪网页| 亚洲产国偷v产偷v自拍涩爱 | 91麻豆成人精品国产 | 男人桶进美女尿囗 | 成人v精品蜜桃久一区 | 久久久久久国产精品免费播放 | 日本黄色不卡 | 清纯唯美亚洲激情 | 国产精品电影网站 | 亚洲国产精品18久久久久久 | 国产又黄视频 | 91免费播放 | 亚洲7777| 国产,日韩,欧美 | 特级丰满少妇一级aaa爱毛片 | av中文天堂在线 | 制服丝袜在线第一页 | 天天插天天干 | 我要色综合天天 | 亚洲依依| 欧美色综合网 | 国产真实自拍 | 日韩毛片在线观看 | 污漫在线观看 | 国产传媒在线 | 人妻在客厅被c的呻吟 | 国产视频在线一区二区 | 国产三级理论 | 黄色网页在线 | 国产中年熟女高潮大集合 | 91福利在线免费观看 | 欧洲精品久久一区二区 | 香蕉国产| 国产视频高清 | 女同av网站 | 老熟女毛茸茸浓毛 | 91精品国产综合久久久蜜臀图片 | 在线免费观看视频黄 | 婷婷久久久 | 超碰男人天堂 | 天堂中文网 | 欧美人人爽| 亚洲视频1 | 成人在线网 | 日本中文字幕不卡 | 国产精品久久777777毛茸茸 | 婷婷激情综合网 | 69色堂| 亚洲人高潮女人毛茸茸 | 日本一区二区在线不卡 | 一级片免费观看 | 中文日韩在线 | 国产一区二区三区成人 | 五月天青青草 | 欧美日韩国产区 | 精品蜜桃一区二区三区 | 骚虎av | 韩国三级丰满少妇高潮 | 91人人爱 | www.爱操| 非洲黑人狂躁日本妞 | 免费看一级片 | 久久久久久久国产精品视频 | 亚洲经典自拍 | 中文字幕不卡视频 | 青青免费在线视频 | 欧美日韩三级在线 | 精品国产黄色片 | 国产精品黄色片 | 丰满少妇麻豆av苏语棠 | 青草成人| 久久国产福利一区 | 欧美日韩国产二区 |