当前位置:网站首页>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
边栏推荐
- Pagoda SSL can't be accessed? 443 port occupied? resolvent
- SQL injection (1) -- determine whether there are SQL injection vulnerabilities
- LV1 Roche limit
- Design and implementation of redis 7.0 multi part AOF
- Www 2022 | taxoenrich: self supervised taxonomy complemented by Structural Semantics
- 機器學習基礎:用 Lasso 做特征選擇
- Examination question bank of constructor decoration direction post skills (constructor) and examination data of constructor decoration direction post skills (constructor) in 2022
- Data collection and summary
- Unity knapsack system (code to center and exchange items)
- Global and Chinese market of contour projectors 2022-2028: Research Report on technology, participants, trends, market size and share
猜你喜欢

The "message withdrawal" of a push message push, one click traceless message withdrawal makes the operation no longer difficult

Buuctf QR code

Comment la transformation numérique du crédit d'information de la Chine passe - t - elle du ciel au bout des doigts?

What is cloud primordial?

中電資訊-信貸業務數字化轉型如何從星空到指尖?

Unspeakable Prometheus monitoring practice

MySQL query
![Stm32bug [stlink forced update prompt appears in keilmdk, but it cannot be updated]](/img/ad/b675364fcaf5d874397fd0cbfec11b.jpg)
Stm32bug [stlink forced update prompt appears in keilmdk, but it cannot be updated]

Rhcsa day 3

96% of the collected traffic is prevented by bubble mart of cloud hosting
随机推荐
Solve the problem that the tabbar navigation at the bottom of vantui does not correspond to the page (window.loading.hash)
Setting methods, usage methods and common usage scenarios of environment variables in postman
MySQL workbench use
Www 2022 | taxoenrich: self supervised taxonomy complemented by Structural Semantics
The requests module uses
Crawler practice website image batch download
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
Package and download 10 sets of Apple CMS templates / download the source code of Apple CMS video and film website
Save Private Ryan - map building + voltage dp+deque+ shortest circuit
What are the conditions for the opening of Tiktok live broadcast preview?
Global and Chinese market for travel wheelchairs 2022-2028: Research Report on technology, participants, trends, market size and share
Amélioration de l'efficacité de la requête 10 fois! 3 solutions d'optimisation pour résoudre le problème de pagination profonde MySQL
Site favorites
Zhihu million hot discussion: why can we only rely on job hopping for salary increase? Bosses would rather hire outsiders with a high salary than get a raise?
false sharing
Zblog collection plug-in does not need authorization to stay away from the cracked version of zblog
Global and Chinese market of small batteries 2022-2028: Research Report on technology, participants, trends, market size and share
Unspeakable Prometheus monitoring practice
Contest3145 - the 37th game of 2021 freshman individual training match_ E: Eat watermelon
MySQL query