Web Development  

How to Implement CSRF Protection in Web Applications Step by Step

Introduction

When building modern web applications, security is not optional—it is essential. One of the most common web security risks is CSRF (Cross-Site Request Forgery). This type of attack can trick users into performing actions they did not intend, such as transferring money, changing passwords, or updating account details.

To build secure and reliable applications, developers must understand how CSRF works and how to prevent it effectively.

In this article, we will learn what CSRF is, how it works, and how to implement CSRF protection step by step using simple words, real examples, and best practices.

What is CSRF (Cross-Site Request Forgery)?

CSRF is a type of attack where a malicious website tricks a user’s browser into sending an unwanted request to another website where the user is already authenticated.

In simple words:

  • The user is logged into a trusted website

  • A malicious site sends a request without the user knowing

  • The trusted site accepts the request because it sees a valid session

This can lead to serious security issues.

How CSRF Attack Works

Let’s understand this with a simple example:

  1. User logs into a banking website

  2. Session is active in the browser

  3. User visits a malicious website

  4. That website sends a hidden request like:

<img src="https://bank.com/transfer?amount=10000&to=attacker" />
  1. The browser automatically sends cookies

  2. Bank processes the request as valid

This happens without user awareness.

Why CSRF Protection is Important?

Implementing CSRF protection is critical because:

  • Prevents unauthorized actions

  • Protects user data and accounts

  • Improves application security

  • Helps meet security standards

  • Builds user trust

Step 1: Use Anti-CSRF Tokens

The most common way to prevent CSRF is using anti-CSRF tokens.

How it works:

  • Server generates a unique token

  • Token is sent to the client (form or header)

  • Client sends token back with request

  • Server validates token

Example (HTML form):

<form method="post">
    <input type="hidden" name="csrf_token" value="ABC123" />
    <button type="submit">Submit</button>
</form>

Server checks if the token is valid.

Step 2: Validate Token on Server

Every request must be validated.

Example (C# ASP.NET Core):

[ValidateAntiForgeryToken]
public IActionResult Submit(FormModel model)
{
    return View();
}

This ensures that only valid requests are processed.

Step 3: Use SameSite Cookies

SameSite cookies help prevent CSRF by restricting how cookies are sent.

Example:

options.Cookie.SameSite = SameSiteMode.Strict;

Types:

  • Strict → cookies not sent in cross-site requests

  • Lax → limited cross-site support

This adds an extra layer of security.

Step 4: Use HTTP Headers for APIs

For APIs, tokens are usually sent in headers.

Example:

X-CSRF-TOKEN: ABC123

Server validates this header before processing.

Step 5: Avoid Using GET for Sensitive Actions

GET requests should never change data.

Bad example:

GET /delete-user?id=1

Better:

POST /delete-user

This reduces CSRF risk.

Step 6: Implement CSRF Protection in JavaScript (AJAX)

When using AJAX, include CSRF token in requests.

Example:

fetch('/api/data', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'X-CSRF-TOKEN': token
    },
    body: JSON.stringify(data)
});

Step 7: Enable Framework-Level Protection

Most frameworks provide built-in CSRF protection.

ASP.NET Core example:

builder.Services.AddControllersWithViews(options =>
{
    options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
});

This automatically protects all unsafe HTTP methods.

Step 8: Use Double Submit Cookie Pattern

In this method:

  • Token is stored in cookie

  • Same token is sent in request

  • Server compares both values

If they match, request is valid.

Step 9: Protect Authentication Endpoints

Ensure login and logout endpoints are also protected.

This prevents attackers from manipulating sessions.

Step 10: Test CSRF Protection

Always test your implementation.

Ways to test:

  • Try sending requests without token

  • Use tools like Postman

  • Perform security testing

Best Practices for CSRF Protection

  • Always use anti-CSRF tokens

  • Validate every request

  • Use SameSite cookies

  • Avoid sensitive GET requests

  • Use HTTPS for secure communication

Common Mistakes to Avoid

  • Not validating tokens on server

  • Using static tokens

  • Ignoring API security

  • Not testing security features

Real-World Use Cases

  • Banking applications

  • E-commerce websites

  • Social media platforms

  • SaaS applications

Summary

CSRF protection is a critical part of web application security. By using techniques like anti-CSRF tokens, SameSite cookies, secure HTTP methods, and proper validation, you can prevent unauthorized actions and protect user data. Implementing CSRF protection step by step ensures your application is secure, reliable, and ready for real-world use.