Do you know what ASP.NET Anti Forgery Tokens are? In the world of web development, security is of paramount importance. With the rise of cyber attacks, developers must ensure their applications are secure and prevent unauthorized access to sensitive data. One common method used to achieve this is through Antiforgery tokens. Antiforgery tokens are used to prevent Cross-Site Request Forgery (CSRF) attacks. In this blog post, we will discuss Antiforgery tokens and how they are used in ASP.NET.
Cross-Site Request Forgey (CSRF) Attacks
Imagine you are at a coffee shop, and you decide to check your bank account using their free Wi-Fi. You click on a legit link and type in your login details. But guess what? That website is fake, created by a hacker. They’re so sneaky that without you realizing it, they automatically submit a request to your bank’s website using your saved login credentials. And since you’re already logged in, the request is authorized, and the hacker can transfer money out of your account without your knowledge or consent.
That’s what a CSRF attack is all about. It’s when a sneaky website tricks you into unknowingly submitting a request to a different website, resulting in unauthorized actions being taken on your behalf.
CSRF Prevention
To prevent CSRF attacks, one common method used is Antiforgery tokens. Antiforgery tokens are generated on the server side and are unique to each user session. They are sent to the client as a hidden form field or a cookie. When the user submits a form, the token is sent back to the server, and the server verifies that the token matches the one generated for the user’s session. If the token does not match or is missing, the server will reject the request.
Antiforgery tokens are generated on the server side and are unique to each user session. They are sent to the client side as a hidden form field or a cookie. When the user submits a form, the token is sent back to the server, and the server verifies that the token matches the one generated for the user’s session. If the token does not match or is missing, the server will reject the request. This prevents a malicious website from tricking a user into unknowingly submitting a request to a different website since the attacker would not have access to the correct Antiforgery token for the user’s session. By generating a unique token for each user session, web apps ensure that requests are legitimate and prevent unauthorized actions from being taken on the user’s behalf.
How Are ASP.NET Antiforgery Tokens Used?
Ignoring Default Token Validation
Antiforgery tokens are enabled for forms in ASP.Net and validated by default. In this article, we’ll disable the default validation behavior and add explicit validation to understand better what happens under the hood. To disable the default token validation behavior globally, you can configure the services in your Program.cs
file like this:
builder.Services.AddControllersWithViews(options => options.Filters.Add(new IgnoreAntiforgeryTokenAttribute()));
Or you can add the attribute to individual controllers.
[IgnoreAntiforgeryToken] public class AuthController: Controller
Now let’s add the explicit validation. ASP.NET Antiforgery tokens are easy to use and require minimal changes to existing code. If you want to skyrocket your C# career, check out our powerful ASP.NET full-stack web development course that also covers test-driven development. You can also learn more about the FluentAssertions library in this post.
Generating Tokens
To use Antiforgery tokens in your ASP.NET application, you must first enable the Antiforgery feature. This is done by adding the @Html.AntiForgeryToken()
method call to your view. This will generate a unique token for each user session.
Asp.Net automatically generates Antiforgery tokens in all forms. We only ignored the validation. In the following form, the token is generated manually. If you are following along, create a new folder under your Views
folder and name it Login.cshtml
, and copy the following code into it.
@Model CredentialsModel; @using (Html.BeginForm()) { @Html.AntiForgeryToken() <input type="text" name="username" /> <input type="password" name="password" /> <button type="submit">Login</button> }
@Html.AntiForgeryToken()
adds a hidden input to the form, and every time the user requests the page, the server generates a new token. As I said, even if you remove it, the framework automatically generates it for you.
This is the model:
public record CredentialsModel(string Username,string Password);
Enforcing Token Validation
Next, you must decorate your controller methods with the [ValidateAntiForgeryToken]
attribute. This tells ASP.NET to validate the Antiforgery token before allowing the request to be processed. If the token is invalid or missing, the server will return a 400 Bad Request error.
Here’s an example of how to use Antiforgery tokens in an ASP.NET application:
public class AuthController : Controller { [HttpGet] public IActionResult Login() => View(); [HttpPost] [ValidateAntiForgeryToken] public IActionResult Login(CredentialsModel credentials) { // Validate Antiforgery token if (!ModelState.IsValid) return BadRequest(); // Validate username and password if (credentials.Username == "Mohsen" && credentials.Password == "1234") // Login successful return RedirectToAction(actionName: "Dashboard", controllerName: "Home"); // else // Login failed ModelState.AddModelError("", "Invalid username or password"); return View(); } }
In this example, we have decorated the HttpPost
Login
method with the [ValidateAntiForgeryToken]
attribute. This ensures that the Antiforgery token is validated every time the client posts the form.
Now you can run the app and navigate to view-source:[<http://localhost:5139/Auth/Login>](<http://localhost:5139/Auth/Login>)
in your browser to see the token:
<input name="__RequestVerificationToken" type="hidden" value="..." />
And every time you refresh the page, you’ll see a new token value.
Conclusion
In conclusion, ASP.NET Antiforgery tokens are an essential security feature that helps protect against CSRF attacks. By generating a unique token for each user session, ASP.NET ensures that requests are legitimate and prevents unauthorized actions from being taken on the user’s behalf. Implementing Antiforgery tokens in your ASP.NET application is a simple process that can greatly enhance its security. By the way, did you know that we offer a unique online course that boosts your C# career? Check it out here!