当前位置:网站首页>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
边栏推荐
- 查詢效率提昇10倍!3種優化方案,幫你解决MySQL深分頁問題
- C # learning notes: structure of CS documents
- Leetcode 110 balanced binary tree
- Setting methods, usage methods and common usage scenarios of environment variables in postman
- Love and self-discipline and strive to live a core life
- Advanced learning of MySQL -- Application -- index
- Li Chuang EDA learning notes IX: layers
- Global and Chinese market of digital impression system 2022-2028: Research Report on technology, participants, trends, market size and share
- Global and Chinese market of cell scrapers 2022-2028: Research Report on technology, participants, trends, market size and share
- Site favorites
猜你喜欢

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

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

Bugku Zhi, you have to stop him

Crawler practice website image batch download

No clue about the data analysis report? After reading this introduction of smartbi, you will understand!

Buuctf QR code

LV1 tire pressure monitoring

MySQL query

Advanced learning of MySQL -- Application -- index
随机推荐
Dare to climb here, you're not far from prison, reptile reverse actual combat case
Rhcsa day 3
How to use STR function of C language
Network communication basic kit -- IPv4 socket structure
Is online futures account opening safe and reliable? Which domestic futures company is better?
FRP intranet penetration
Zblog collection plug-in does not need authorization to stay away from the cracked version of zblog
Create real-time video chat in unity3d
Love and self-discipline and strive to live a core life
長文綜述:大腦中的熵、自由能、對稱性和動力學
Key knowledge of C language
Database concept and installation
Li Chuang EDA learning notes IX: layers
What are the conditions for the opening of Tiktok live broadcast preview?
1day vulnerability pushback skills practice (3)
Keep an IT training diary 055- moral bitch
Global and Chinese markets for electroencephalogram (EEG) devices 2022-2028: Research Report on technology, participants, trends, market size and share
JS object definition
PHP database connection succeeded, but data cannot be inserted
PTA tiantisai l1-079 tiantisai's kindness (20 points) detailed explanation