Cross-Site Request Forgery (CSRF) is a type of security vulnerability that allows an attacker to trick a user into executing unwanted actions on a web application in which they are authenticated. This can lead to unauthorized actions being performed on behalf of the user without their consent.

How CSRF Works

CSRF exploits the trust that a web application has in the user's browser. For example, if a user is logged into a banking application and visits a malicious website, that website could send a request to the banking application to transfer funds without the user's knowledge.

Preventing CSRF in ASP.NET MVC

ASP.NET MVC provides built-in mechanisms to prevent CSRF attacks. The most common method is to use Anti-Forgery Tokens. These tokens are unique for each user session and are included in forms to ensure that the request is coming from a legitimate source.

Step 1: Adding Anti-Forgery Token in Views

To include an Anti-Forgery Token in your forms, you can use the @Html.AntiForgeryToken() helper method. Here’s an example of a simple form:

        
<form method="post" action="/Account/ChangePassword">
@Html.AntiForgeryToken()
<label for="newPassword">New Password:</label>
<input type="password" id="newPassword" name="newPassword" required />
<button type="submit">Change Password</button>
</form>

Step 2: Validating Anti-Forgery Token in Controller

In your controller action, you need to validate the Anti-Forgery Token. This is done automatically by using the [ValidateAntiForgeryToken] attribute. Here’s how you can implement it:

        
using System.Web.Mvc;

public class AccountController : Controller
{
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ChangePassword(string newPassword)
{
// Logic to change the password
return RedirectToAction("Index");
}
}

Conclusion

By implementing Anti-Forgery Tokens in your ASP.NET MVC applications, you can significantly reduce the risk of CSRF attacks. Always ensure that you validate these tokens on the server side to maintain the integrity of user actions.