MVC Ajax submission is to prevent SCRF attacks

Source: Internet
Author: User

In the View
<script type="Text/javascript">@functions { Public stringTokenheadervalue () {stringCookietoken,fromtoken; Antiforgery.gettokens (NULL, outCookietoken, outFromtoken); returncookietoken+":"+Fromtoken;  }} $function ({... $.ajax ("Api/value", {data:{...}, type:'Post', DataType:'JSON', headers:{'Requestverificationtoken':'@ToKenHeaderValue ()'}, Success:fucntion (data) {...} })})</script>

//self-written filter


1 Public classMyvalidateantiforgerytokenattribute:fileterattribute,iauthorizationfilter2 {3 Private voidValidaterequestheader (httprequestbase request)4 { 5 stringcookietoken="";6 stringfromtoken="";7 stringTokenvalue=request. header["Requestverificationtoken"];8 if(!string. IsNullOrEmpty (tokenvalue))9 {Ten string[] Tokens=tokenvalue.split (':'); One if(Tokens. Length=2) A { -cookietoken=tokens[0]. Trim (); -fromtoken=tokens[1]. Trim (); the } - } - antiforgery.validate (cookietoken,fromtoken); - } +}
public void Onauthiorization (Authorizationcontexte context)
21 {
Try
23 {
if (context. HttpContext.Request.IsAjaxRequest ())//Determine if Ajax commits
25 {
Validaterequetheader (context. HttpContext.Request);
27}
-Else
Antiforgery.validate ();
30}
Catch
32 {
Httpantiforgeryexception throw new ("...");
34}


In the Controller's action

1 [httppost]//indicates post submission
2 [myvalidateantiforgerytoken]//here calls its own write filter to prevent CSRF attacks
3 Public actionresult Value () 4 {5 ..... 6 }

Reference: Preventing Cross-site Request Forgery (CSRF) Attacks

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.