.net core 一个避免跨站请求的中间件
生活随笔
收集整理的這篇文章主要介紹了
.net core 一个避免跨站请求的中间件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前提:
? ? ??前幾天看到博客園首頁中有這么一篇文章:跨站請求偽造(CSRF),剛好前段時間自己一直也在搞這個東西,后來覺得每次在form表單里添加一個@Html.AntiForgeryToken,在對應的方法上添加特性[ValidateAntiForgeryToken],很是麻煩,于是自己動手寫了一個全局的中間件,只要是post請求就會生成一個表單驗證的token。
? ? ? ? 話不多說,上代碼;
? ? ? 核心代碼:
1 public class GlobalValidateMiddleTool 2 { 3 private RequestDelegate _requestDelete; 4 private IAntiforgery _antiforgery; 5 public GlobalValidateMiddleTool(RequestDelegate requestDelegate,IAntiforgery antiforgery) 6 { 7 _requestDelete = requestDelegate; 8 _antiforgery = antiforgery; 9 } 10 public async Task Invoke(HttpContext context) 11 { 12 if (context.Request.Method.ToLower() == "post") 13 { 14 await _antiforgery.ValidateRequestAsync(context); 15 } 16 await _requestDelete(context); 17 } 18 }?
一個拓展方法:
1 public static class IapplicationExt 2 { 3 public static IApplicationBuilder UseGlobalTokenValidate(this IApplicationBuilder app) 4 { 5 return app.UseMiddleware<GlobalValidateMiddleTool>(); 6 } 7 }使用方法:
app.UseGlobalTokenValidate();驗證一下,寫了一個form表單
<form asp-action="about" method="post"><input type="text" id="data" name="data" /><input type="submit" value="test" /> </form>對應的action?
[HttpPost]public IActionResult About(string data){if (ModelState.IsValid){return Json(data);}return NotFound();}界面:
表單中填寫test 點擊提交按鈕
?
?返回結果:
這樣就表示我們的這個中間件生效了。
轉載于:https://www.cnblogs.com/qulianqing/p/7757728.html
總結
以上是生活随笔為你收集整理的.net core 一个避免跨站请求的中间件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: (三)3-1 练习
- 下一篇: android的百度地图开发(二) 定位