
Before discussing this we need to know what CSRF (Cross Site Request Forgery) is?
Here CSRF is an attack where malicious site sends a request to a vulnerable site where the user is currently logged in.
Let us see an example of a CSRF attack will work:
- Suppose user logged in a particular site like www.smarterp.com and then without signing off user clicked some malicious site. See Fig1
- Once user click the malicious site then the user’s smarterp mail id will be updated with hacker’s mail id hacker@gmail.com. This is the “Cross-site” Part of CSRF.
- Next hacker will go to the login page of www.smarterp.com, he’ll click “forgot password”. To recover the password, site will ask for mail id then hacker will provide the same which was updated earlier in user’s records, then to reset password smarterp site will send recovery mail to hacker’s mail id, then hacker can get account credentials and he can do whatever he want.
<html>
<head>
<title>Important</title>
</head>
<body>
<formaction=”http://smarterp.com/api/account”method=”post”>
<h1>Earn $7487 month working from home on the Internet</h1>
<inputtype=”hidden”name=”Email”value=”hacker@gmail.com”/>
<inputtype=”submit”value=”Ok”/>
</form>
</body>
</html>
Fig 1
Anti – Forgery Tokens:
To prevent CSRF attacks, ASP.NET provides Anti-Forgery Tokens.
When user request the webpage then the server will generate two tokens randomly and send to user as a response. One token will send as a cookie and another token will be as a hidden field in the form
When the user submits the form, then the browser will send the cookie token as a cookie and form token inside the form data.
If a browser won’t send both the tokens then the server won’t allow to submit the form.
Here is the example of an HTML form with a hidden form token:
<formaction=”/Employee/Save”method=”post”>
<inputname=”__RequestVerificationToken”type=”hidden”
value=”6fGBtLZmVBZ59oUad1Fr33BuPxANKY9q3Srr5y[...]“/>
<inputtype=”submit”value=”Submit”/>
</form>
To prevent CSRF attacks and any non-safe methods like POST, DELETE use Anti-Forgery Token. Also, make sure that safe methods (GET) do not have any side effects.
How to use Anti-Forgery Tokens in ASP.NET MVC?
To use Anti-Forgery token in MVC Razor Page, we use Html.AntiForgeryToken() method
@using (Html.BeginForm(“Employee”, “Save”)) {
@Html.AntiForgeryToken()
}
This method adds the hidden form field and also sets the cookie token.
To add the anti-forgery token to an action method of a Controller we have to use [ValidateAntiForgeryToken] Attribute like the below example.
[HttpPost]
[ValidateAntiForgeryToken]
publicActionResult Save(DataViewModel data)
{
}
If we use both @Html.AntiForgeryToken() and [ValidateAntiForgeryToken] for postmethod then we can prevent CSRF attacks for only post methods.
Thus this is about “Anti-Forgery Token”.
By: Jayasankar J