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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

Swagger在header中添加token

發布時間:2023/12/4 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Swagger在header中添加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 {/// <summary>/// swagger請求頭/// </summary>public class HttpHeaderOperationFilter : IOperationFilter{/// <summary>////// </summary>/// <param name="operation"></param>/// <param name="context"></param>public void Apply(Operation operation, OperationFilterContext context){#region 新方法if (operation.Parameters == null){operation.Parameters = new List<IParameter>();}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

/// <summary>////// </summary>/// <param name="services"></param>// 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<IControllerActivator, ServiceBasedControllerActivator>());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<MvcOptions>(options =>{options.Filters.Add(new CorsAuthorizationFilterFactory("AllowSameDomain"));});#region Swaggerservices.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<HttpHeaderOperationFilter>();c.DocumentFilter<HiddenApiFilter>();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 MiniProfilerif (bool.Parse(Configuration["IsUseMiniProfiler"])){//https://www.cnblogs.com/lwqlun/p/10222505.htmlservices.AddMiniProfiler(options =>options.RouteBasePath = "/profiler").AddEntityFramework();}#endregion MiniProfilerservices.AddDbContext<EFCoreDBContext>(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 {/// <summary>/// 權限/// </summary>public class BasicAuth : ActionFilterAttribute{/// <summary>////// </summary>/// <param name="context"></param>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]

/// <summary>/// 添加/// </summary>/// <param name="model"></param>/// <returns>主鍵id</returns>[BasicAuth][ModelValidationAttribute][ApiExplorerSettings(GroupName = "v1")][HttpPost, Route("Create")]public async Task<ResultDto<long>> 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在header中添加token的全部內容,希望文章能夠幫你解決所遇到的問題。

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