当前位置:网站首页>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
边栏推荐
- WP collection plug-in free WordPress collection hang up plug-in
- Optimization theory: definition of convex function + generalized convex function
- Backpropagation formula derivation [Li Hongyi deep learning version]
- Take you to master the formatter of visual studio code
- Mysql to PostgreSQL real-time data synchronization practice sharing
- 15. System limitations and options
- Johnson–Lindenstrauss Lemma
- C learning notes: C foundation - Language & characteristics interpretation
- Advanced learning of MySQL -- Application -- index
- Baijia forum the founding of the Eastern Han Dynasty
猜你喜欢

A brief talk on professional modeler: the prospect and professional development of 3D game modeling industry in China

Li Chuang EDA learning notes 13: electrical network for drawing schematic diagram
![[Yugong series] February 2022 attack and defense world advanced question misc-83 (QR easy)](/img/36/e5b716f2f976eb474b673f85363dae.jpg)
[Yugong series] February 2022 attack and defense world advanced question misc-83 (QR easy)

Package and download 10 sets of Apple CMS templates / download the source code of Apple CMS video and film website

Imperial cms7.5 imitation "D9 download station" software application download website source code

ZABBIX API pulls the values of all hosts of a monitoring item and saves them in Excel

Take you to master the formatter of visual studio code

Unity knapsack system (code to center and exchange items)

在尋求人類智能AI的過程中,Meta將賭注押向了自監督學習

Www 2022 | taxoenrich: self supervised taxonomy complemented by Structural Semantics
随机推荐
Mysql to PostgreSQL real-time data synchronization practice sharing
Mysql-15 aggregate function
Keep an IT training diary 055- moral bitch
Baijia forum the founding of the Eastern Han Dynasty
The "message withdrawal" of a push message push, one click traceless message withdrawal makes the operation no longer difficult
Imperial cms7.5 imitation "D9 download station" software application download website source code
Li Chuang EDA learning notes 13: electrical network for drawing schematic diagram
Osnabrueck University | overview of specific architectures in the field of reinforcement learning
Redis transaction
Fudan released its first review paper on the construction and application of multimodal knowledge atlas, comprehensively describing the existing mmkg technology system and progress
[Yugong series] February 2022 attack and defense world advanced question misc-84 (MySQL)
WP collection plug-in free WordPress collection hang up plug-in
[untitled] the relationship between the metauniverse and digital collections
SQL injection (1) -- determine whether there are SQL injection vulnerabilities
[Wu Enda deep learning] beginner learning record 3 (regularization / error reduction)
POSTECH | option compatible reward reverse reinforcement learning
查詢效率提昇10倍!3種優化方案,幫你解决MySQL深分頁問題
LV1 Roche limit
Dans la recherche de l'intelligence humaine ai, Meta a misé sur l'apprentissage auto - supervisé
Libcblas appears when installing opencv import CV2 so. 3:cannot open shared object file:NO such file or directory