当前位置:网站首页>Add token validation in swagger
Add token validation in swagger
2022-07-04 03:01:00 【Up technical control】
Usually do project use mvc+webapi, Take the way of separating the front and rear ends , Background offering API Interface to front-end developers . There is a problem in this process. How can the background developers provide interface description documents to front-end developers . To solve this problem , Quote in the project swagger( I prefer to call it “ Brother stockings ”).
List all API Controller and controller description

Well, since it is api, There must be security verification involved , So how to add to the test document Token What about security verification ;
Let's take a look at
1、 Definition swagger Request header
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 Request header/// </summary>public class HttpHeaderOperationFilter : IOperationFilter{/// <summary>////// </summary>/// <param name="operation"></param>/// <param name="context"></param>public void Apply(Operation operation, OperationFilterContext context){#region The new methodif (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 = " Please enter Token, The format is bearer XXX"});}}#endregion The new method}}}
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
2、 stay ConfigureServices Method add 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"});// A lowercase letteroptions.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 = " Interface document ",Description = " Interface document - Basics ",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 = " Interface document ",Description = " Interface document - Basics ",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<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);}
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
3、 Define a 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>/// jurisdiction/// </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);}}}
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
4、 Finally, use it where necessary [BasicAuth]
/// <summary>/// add to/// </summary>/// <param name="model"></param>/// <returns> Primary key 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());}
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
- 1.
We can see Authorization - Please enter Token, The format is bearer XXX

Source code address :
https://github.com/conanl5566/Sampleproject/tree/master/src/03%20Host/CompanyName.ProjectName.HttpApi.Host
边栏推荐
- [Yugong series] February 2022 attack and defense world advanced question misc-83 (QR easy)
- C learning notes: C foundation - Language & characteristics interpretation
- The difference between MCU serial communication and parallel communication and the understanding of UART
- 15. System limitations and options
- Fudan released its first review paper on the construction and application of multimodal knowledge atlas, comprehensively describing the existing mmkg technology system and progress
- Take you to master the formatter of visual studio code
- Global and Chinese markets for electroencephalogram (EEG) devices 2022-2028: Research Report on technology, participants, trends, market size and share
- Site favorites
- Enhanced for loop
- 中電資訊-信貸業務數字化轉型如何從星空到指尖?
猜你喜欢

Li Chuang EDA learning notes IX: layers

I stepped on a foundation pit today

The 37 year old programmer was laid off, and he didn't find a job for 120 days. He had no choice but to go to a small company. As a result, he was confused

Save Private Ryan - map building + voltage dp+deque+ shortest circuit
![Measurement fitting based on Halcon learning [4] measure_ arc. Hdev routine](/img/3a/cf6285ae1c01bda42874eeca9fe5b1.jpg)
Measurement fitting based on Halcon learning [4] measure_ arc. Hdev routine

Buuctf QR code

This function has none of DETERMINISTIC, NO SQL..... (you *might* want to use the less safe log_bin_t

The difference between MCU serial communication and parallel communication and the understanding of UART

Database concept and installation

Take you to master the formatter of visual studio code
随机推荐
LV1 previous life archives
The difference between int (1) and int (10)
Global and Chinese market of cell scrapers 2022-2028: Research Report on technology, participants, trends, market size and share
Global and Chinese markets of advanced X-ray inspection system (Axi) in PCB 2022-2028: Research Report on technology, participants, trends, market size and share
Keep an IT training diary 054- opening and closing
Talking about custom conditions and handling errors in MySQL Foundation
FRP intranet penetration
What are the conditions for the opening of Tiktok live broadcast preview?
Ai aide à la recherche de plagiat dans le design artistique! L'équipe du professeur Liu Fang a été embauchée par ACM mm, une conférence multimédia de haut niveau.
Global and Chinese market of contour projectors 2022-2028: Research Report on technology, participants, trends, market size and share
STM32 key content
Sword finger offer 20 String representing numeric value
String: LV1 eat hot pot
Basé sur... Netcore Development blog Project Starblog - (14) Implementation of theme switching function
Hospital network planning and design document based on GLBP protocol + application form + task statement + opening report + interim examination + literature review + PPT + weekly progress + network to
(practice C language every day) pointer sorting problem
Is online futures account opening safe and reliable? Which domestic futures company is better?
1day vulnerability pushback skills practice (3)
Key knowledge of embedded driver
The "message withdrawal" of a push message push, one click traceless message withdrawal makes the operation no longer difficult