首页 > 代码库 > MVC Ajax 提交是防止SCRF攻击

MVC Ajax 提交是防止SCRF攻击

//在View中
<script type="text/javascript">  @functions{    public string ToKenHeaderValue()   {        string cookieToken,fromToken;        AntiForgery.GetTokens(null,out cookieToken,out fromToken);        return  cookieToken+":"+fromToken;   }}$function({  。。。。。  $.ajax("api/Value",{   data:{...},    type:post,   dataType:json,   headers:{RequestVerificationToKen:@ToKenHeaderValue()},  success:fucntion(data){....}   })})</script>

 

//自己写的过滤器


1
public class MyValidateAntiForgeryToKenAttribute:FileterAttribute,IAuthorizationFilter 2 { 3 private void ValidateRequestHeader(HttpRequestBase request) 4 { 5 string cookieToKen=""; 6 string fromToKen=""; 7 string tokenValue=http://www.mamicode.com/request.Header["RequestVerificationToKen"]; 8 if(!string.IsNullOrEmpty(tokenValue)) 9 {10 string[] tokens=tokenValue.Split(:);11 if(tokens.Length=2)12 {13 cookieToken=tokens[0].Trim();14 fromToKen=tokens[1].Trim();15 }16 }17 AntiForGery.Validate(cookieToken,fromToken);18 }19 }
20 public void OnAuthiorization(AuthorizationContexte context)
21 {
22 try
23 {
24 if(context.HttpContext.Request.IsAjaxRequest())//判断是否ajax提交
25 {
26 ValidateRequetHeader(context.HttpContext.Request);
27 }
28 else
29 AntiForgery.Validate();
30 }
31 catch
32 {
33 throw new HttpAntiForgeryException("...");
34 }


 

 在Controller的Action中

1 [HttpPost]//指示POST提交
2 [MyValidateAntiForgeryToKen]//这儿调用自己写的过滤器,实现防止CSRF攻击
3 public ActionResult Value()4 {5 .......6 }

 

 

 

参考:Preventing Cross-Site Request Forgery (CSRF) Attacks