简单的网站设计多少钱,山西省确诊病例最新情况,怎么百度做网站,如何备份网站 整站公开API的安全#xff0c;其实更重要。一、API的安全作为一个Dotnet Core的老司机#xff0c;写API时#xff0c;能兼顾到API的安全#xff0c;这是一种优雅。通常#xff0c;我们会用认证来保证API的安全#xff0c;无敌的Authorize能解决我们很多的问题。但是#xff… 公开API的安全其实更重要。 一、API的安全作为一个Dotnet Core的老司机写API时能兼顾到API的安全这是一种优雅。 通常我们会用认证来保证API的安全无敌的Authorize能解决我们很多的问题。但是总有一些场合我们没办法用Authorize而只能用匿名或不加验证的方式来访问。比方电商中查询SKU的列表并在前端展示通常这个无关用户和权限在完成API的时候我们也不会加入认证Authorize。这种情况下如果直接写不加入安全级别这样的体系结构是有可能成为可供利用的安全漏洞的。 Dotnet Core框架已经提供了一些常见漏洞的解决方法包括跨站点脚本SQL注入跨站点请求伪造CSRF重定向等等。但是我们还需要更进一步还需要照顾到以下常见的攻击拒绝服务DOS分布式拒绝服务DDOS批量API调用探测响应数据抓取这部分内容需要我们自己实现。当然这部分内容的实现也可以从Web Server上进行设置。本文讨论的是代码的实现。二、相关代码今天偷个懒不讲原理以分享代码为主。2.1 基于IP的客户端请求限制通过限制客户端在指定的时间范围内的请求数量防止恶意bot攻击。代码中我建立了一个基于IP的请求限制过滤器。注意有多个客户端位于同一个IP地址的情况这个情况在这个代码中没有考虑。如果您希望实现这一点可以把几种方式结合起来使用。以下是代码[AttributeUsage(AttributeTargets.Method)]
public class RequestLimitAttribute : ActionFilterAttribute
{public string Name { get; }public int NoOfRequest { get; set; }public int Seconds { get; set; }private static MemoryCache Cache { get; } new MemoryCache(new MemoryCacheOptions());public RequestLimitAttribute(string name, int noOfRequest 5, int seconds 10){Name name;NoOfRequest noOfRequest;Seconds seconds;}public override void OnActionExecuting(ActionExecutingContext context){var ipAddress context.HttpContext.Request.HttpContext.Connection.RemoteIpAddress;var memoryCacheKey ${Name}-{ipAddress};Cache.TryGetValue(memoryCacheKey, out int prevReqCount);if (prevReqCount NoOfRequest){context.Result new ContentResult{Content $Request limit is exceeded. Try again in {Seconds} seconds.,};context.HttpContext.Response.StatusCode (int)HttpStatusCode.TooManyRequests;}else{var cacheEntryOptions new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromSeconds(Seconds));Cache.Set(memoryCacheKey, (prevReqCount 1), cacheEntryOptions);}}
}
使用时只要在需要的API前加属性即可[HttpGet]
[RequestLimit(DataGet, 5, 30)]
public IEnumerableWeatherForecast Get()
{...
}
2.2 引用头检查对API请求的请求引用头进行检查可以防止API滥用以及跨站点请求伪造(CSRF)攻击。同样也是采用自定义属性的方式。public class ValidateReferrerAttribute : ActionFilterAttribute
{private IConfiguration _configuration;public override void OnActionExecuting(ActionExecutingContext context){_configuration (IConfiguration)context.HttpContext.RequestServices.GetService(typeof(IConfiguration));base.OnActionExecuting(context);if (!IsValidRequest(context.HttpContext.Request)){context.Result new ContentResult{Content $Invalid referer header,};context.HttpContext.Response.StatusCode (int)HttpStatusCode.ExpectationFailed;}}private bool IsValidRequest(HttpRequest request){string referrerURL ;if (request.Headers.ContainsKey(Referer)){referrerURL request.Headers[Referer];}if (string.IsNullOrWhiteSpace(referrerURL)) return true;var allowedUrls _configuration.GetSection(CorsOrigin).Getstring[]()?.Select(url new Uri(url).Authority).ToList();bool isValidClient allowedUrls.Contains(new Uri(referrerURL).Authority);return isValidClient;}
}
这里我用了一个配置在appsetting.json中{CorsOrigin: [https://test.com, http://test1.cn:8080]
}
CorsOrigin参数中加入允许引用的来源域名:端口列表。使用时在需要的API前加属性[HttpGet]
[ValidateReferrer]
public IEnumerableWeatherForecast Get()
{...
}
2.3 DDOS攻击检查DDOS攻击在网上很常见这种攻击简单有效可以让一个网站瞬间开始并长时间无法响应。通常来说网站可以通过多种节流方法来避免这种情况。下面我们换一种方式用中间件MiddleWare来限制特定客户端IP的请求数量。public class DosAttackMiddleware
{private static Dictionarystring, short _IpAdresses new Dictionarystring, short();private static Stackstring _Banned new Stackstring();private static Timer _Timer CreateTimer();private static Timer _BannedTimer CreateBanningTimer();private const int BANNED_REQUESTS 10;private const int REDUCTION_INTERVAL 1000; // 1 second private const int RELEASE_INTERVAL 5 * 60 * 1000; // 5 minutes private RequestDelegate _next;public DosAttackMiddleware(RequestDelegate next){_next next;}public async Task InvokeAsync(HttpContext httpContext){string ip httpContext.Connection.RemoteIpAddress.ToString();if (_Banned.Contains(ip)){httpContext.Response.StatusCode (int)HttpStatusCode.Forbidden;}CheckIpAddress(ip);await _next(httpContext);}private static void CheckIpAddress(string ip){if (!_IpAdresses.ContainsKey(ip)){_IpAdresses[ip] 1;}else if (_IpAdresses[ip] BANNED_REQUESTS){_Banned.Push(ip);_IpAdresses.Remove(ip);}else{_IpAdresses[ip];}}private static Timer CreateTimer(){Timer timer GetTimer(REDUCTION_INTERVAL);timer.Elapsed new ElapsedEventHandler(TimerElapsed);return timer;}private static Timer CreateBanningTimer(){Timer timer GetTimer(RELEASE_INTERVAL);timer.Elapsed delegate {if (_Banned.Any()) _Banned.Pop();};return timer;}private static Timer GetTimer(int interval){Timer timer new Timer();timer.Interval interval;timer.Start();return timer;}private static void TimerElapsed(object sender, ElapsedEventArgs e){foreach (string key in _IpAdresses.Keys.ToList()){_IpAdresses[key]--;if (_IpAdresses[key] 0) _IpAdresses.Remove(key);}}
}
代码中设置1秒1000ms中有超过10次访问时对应的IP会被禁用5分钟。使用时在Startup.cs中直接加载中间件public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{...app.UseMiddlewareDosAttackMiddleware();...
}
三、结尾的话以上代码仅为抛砖引玉之用。公开的API未经验证的API在生产环境会因为种种原因被攻击。这几天公司的系统就因为这个出了大事。所以写API的时候要充分考虑到这些网络攻击的可能性通过正确的处理来防止来自网络的攻击。这是一份责任也是一个理念。与大家共勉 全文完 本文的代码我已经传到Github上位置在https://github.com/humornif/Demo-Code/tree/master/0021/demo喜欢就来个三连让更多人因你而受益