Previous Blog - Data Annotation in ASP.Net MVC
Secure MVC form using Anti-Forgery TokenAnti-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 -
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.
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.