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
{
private void ValidateRequestHeader(HttpRequestBase request)
{
string cookieToKen="";
string fromToKen="";
string tokenValue=request.Header["RequestVerificationToKen"];
if(!string.IsNullOrEmpty(tokenValue))
{
string[] tokens=tokenValue.Split(':');
if(tokens.Length=)
{
cookieToken=tokens[].Trim();
fromToKen=tokens[].Trim();
}
}
AntiForGery.Validate(cookieToken,fromToken);
}
}
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中

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

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

上一篇:在windows上,使用虚拟机安装苹果操作系统


下一篇:C扩展Python