ValidateAntiForgeryToken MVC5活用验证
前端
// 获取生成的token,直接这样写也是可以的 function gettoken() { var token = ‘@Html.AntiForgeryToken()‘; return $(token).val(); } //某button的单击事件 function tijiao() { $.ajax({ url:"/Default/Index2", type:‘post‘, data:{name:‘你就‘,__RequestVerificationToken:gettoken() }, success:function (res){ alert(res); } }); }
自定义的特性,方法执行前的特性,检查token
public class MyValidateAntiForgeryToken : AuthorizeAttribute { public override void OnAuthorization(AuthorizationContext filterContext) { var request = filterContext.HttpContext.Request; if (request.HttpMethod == WebRequestMethods.Http.Post && request.Url.Host.ToLower() != WebConfigBLL.LIVE_VZAN_DOMAIN.ToLower()) { HttpCookie antiForgeryCookie = request.Cookies[AntiForgeryConfig.CookieName]; string cookieValue = antiForgeryCookie != null ? antiForgeryCookie.Value : null; //从cookies 和 Headers 中 验证防伪标记 如果验证不通过会抛出异常 try { // AntiForgery.Validate在NetCore中没有的 AntiForgery.Validate(cookieValue, request["__RequestVerificationToken"]);//验证 HTML 表单字段中的输入数据是否来自已提交数据的用户。 } catch (Exception ex) { filterContext.Result = new ContentResult() { Content = "抱歉,登录异常!", ContentEncoding = System.Text.Encoding.UTF8 }; return; } } } }
把 MyValidateAntiForgeryToken 加到方法上
[HttpPost] [MyValidateAntiForgeryToken] public ActionResult Index2(int id) { //如果前端传值的__RequestVerificationToken验证直接返回验证错误 return View(); }
二:ValidateAntiForgeryTokenAttribute,MVC5和NetCore 通用
<form> @Html.AntiForgeryToken() <input type="text" name="name" value="" placeholder="输入name" /> <input type="text" name="area" value="" placeholder="输入地址" /> <input type="submit" name="sub" value="表单提交" /> </form> var token = $(‘[name=__RequestVerificationToken]‘)[0].value; //这样也可以拿到 $("form").submit(function () { $.ajax({ url: "", type: ‘post‘, /*__RequestVerificationToken放在请求头中,是没有效果的,是必须作为参数传递的*/ //beforeSend: function (XMLHttpRequest) { // XMLHttpRequest.setRequestHeader("__RequestVerificationToken", gettoken()); //}, data: $("form").serializeArray() , dataType: ‘json‘, success: function (res) { alert(res); }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert(errorThrown); } }); return false; });
2.后台,使用自带API,验证错误的话,直接返回400
// [AcceptVerbs(HttpVerbs.Post)] netCore没有这个 [HttpPost] [ValidateAntiForgeryToken] public JsonResult Index(IFormCollection collection) { ModelState.AddModelError("", "1111111111111"); return Json("好的"); }
相关推荐
liuweiyan 2020-02-20
liuweiyan 2020-02-03
rola0 2020-01-29
sdtsfhh 2020-01-29
yusongwhu 2020-01-29
laofangzi 2019-10-26
mvc0 2019-06-26
mvc0 2019-06-26
laofangzi 2019-06-26
honeyht 2019-06-25
yusongwhu 2014-10-28
闲来也无事 2016-08-11
zhoujn 2016-08-11
洗尽铅华 2015-02-25
探秘 2019-04-13
duyelang 2019-04-13