ASP.NET Core MVC Interview Question #117
How does anti-forgery token validation work in MVC?
Authentication, Authorization, Security & State Management Mid-Level Intermediate
Quick Interview Answer
The application issues anti-forgery information to the client and expects the matching token information to be returned with a protected request. MVC validates the token before allowing the action to continue.
Detailed Explanation
The application issues anti-forgery information to the client and expects the matching token information to be returned with a protected request. MVC validates the token before allowing the action to continue.
Form Tag Helpers participate in token generation for normal MVC forms. The corresponding POST action can use ValidateAntiForgeryToken, or applications can configure broader automatic validation conventions.
Code Example
<form asp-action="Delete" method="post">
<input type="hidden" name="id" value="@Model.Id" />
<button type="submit">Delete</button>
</form>
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Delete(int id) => RedirectToAction("Index");