ASP.NET MVC ajax提交 防止CSRF攻击
//在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>
//自己写的过滤器
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=2)
{
cookieToken=tokens[0].Trim();
fromToKen=tokens[1].Trim();
}
}
AntiForGery.Validate(cookieToken,fromToken);
}
}
public void OnAuthiorization(AuthorizationContexte context)
{
try
{
if(context.HttpContext.Request.IsAjaxRequest())//判断是否ajax提交
{
ValidateRequetHeader(context.HttpContext.Request);
}
else
AntiForgery.Validate();
}
catch
{
throw new HttpAntiForgeryException("...");
}
在Controller的Action中
1 [HttpPost]//指示POST提交
2 [MyValidateAntiForgeryToKen]//这儿调用自己写的过滤器,实现防止CSRF攻击
3 public ActionResult Value()
4 {
5 .......
6 }