Anti-forgery tokens in MVC

In this blog, we will see Anti-forgery tokens in MVC. This is a built-in functionality in MVC given by Microsoft. This is a security aspect in ASP.NET MVC.
Previous Blog - Data Annotation in ASP.Net MVC

Secure MVC form using Anti-Forgery Token

Anti-forgery token is used to secure the application against Cross-Site Request Forgery (CSRF).

What is CSRF (Cross Site Request Forgery)?

Suppose, a user is logged in to a website and left the page open without logging out.
A hacker may use a malicious page and share this URL behind and image to user(s) via SMS or email.
He can write a few lines of script to complete the action on behalf of the actual user(s), as the connection is live and the session is active for the actual user. This is called Cross-Site Request Forgery (CSRF).

How Anti-Forgery Tokens helps to protect from CSRF?


In our MVC form page, i.e.on View just add this line -
@Html.AntiForgeryToken();

This method will create a token similar to a secret code, it keeps this value in a hidden field and also as a cookie on user's computer.

So whenever you request a data from the server, a RequestVerificationToken is generated as shown in below screen shot.

You may find these details by pressing F12 (developer tools) in Chrome, Firefox or any browser.



Or inspect your form by using developer tools and search for RequestVerificationToken, same can be found in View Source as well.



So, whenever user posts a form we get these 2 values one from hidden field and another one from Cookies and compare them. If the value matches, it means this is an actual request otherwise it is an attack because a hacker will not have cookies on his/her machine.

Next-



Comments

Popular

What's new in C# 6.0 language - All new features of C# 6.0 for developers

SharePoint Interview Questions and Answers