当前位置:网站首页>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 method
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 = " 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 letter
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 Swagger
services.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 MiniProfiler
if (bool.Parse(Configuration["IsUseMiniProfiler"]))
{
//https://www.cnblogs.com/lwqlun/p/10222505.html
services.AddMiniProfiler(options =>
options.RouteBasePath = "/profiler"
).AddEntityFramework();
}
#endregion MiniProfiler
services.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
边栏推荐
- Remote work guide
- Global and Chinese market of digital impression system 2022-2028: Research Report on technology, participants, trends, market size and share
- Dare to climb here, you're not far from prison, reptile reverse actual combat case
- Contest3145 - the 37th game of 2021 freshman individual training match_ 1: Origami
- Design and implementation of redis 7.0 multi part AOF
- ZABBIX API pulls the values of all hosts of a monitoring item and saves them in Excel
- LV1 Roche limit
- 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
- The difference between MCU serial communication and parallel communication and the understanding of UART
- I stepped on a foundation pit today
猜你喜欢
No clue about the data analysis report? After reading this introduction of smartbi, you will understand!
Lichuang EDA learning notes 14: PCB board canvas settings
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?
7 * 24-hour business without interruption! Practice of applying multiple live landing in rookie villages
Backpropagation formula derivation [Li Hongyi deep learning version]
Kiss number + close contact problem
Li Chuang EDA learning notes 13: electrical network for drawing schematic diagram
Problems and solutions of several concurrent scenarios of redis
PHP database connection succeeded, but data cannot be inserted
Unity controls the selection of the previous and next characters
随机推荐
Zblog collection plug-in does not need authorization to stay away from the cracked version of zblog
Libcblas appears when installing opencv import CV2 so. 3:cannot open shared object file:NO such file or directory
Node solves cross domain problems
機器學習基礎:用 Lasso 做特征選擇
Rhcsa day 3
Pagoda SSL can't be accessed? 443 port occupied? resolvent
Sword finger offer 14- I. cut rope
Question d: Haffman coding
false sharing
Ningde times and BYD have refuted rumors one after another. Why does someone always want to harm domestic brands?
Dare to climb here, you're not far from prison, reptile reverse actual combat case
Latex tips slash \backslash
Data collection and summary
Www 2022 | taxoenrich: self supervised taxonomy complemented by Structural Semantics
The "message withdrawal" of a push message push, one click traceless message withdrawal makes the operation no longer difficult
C learning notes: C foundation - Language & characteristics interpretation
150 ppt! The most complete "fair perception machine learning and data mining" tutorial, Dr. AIST Toshihiro kamishima, Japan
Keepalived set the master not to recapture the VIP after fault recovery (it is invalid to solve nopreempt)
Practical multifunctional toolbox wechat applet source code / support traffic master
Setting methods, usage methods and common usage scenarios of environment variables in postman