Home Website SecurityHow to Configure Csrf Step by Step

How to Configure Csrf Step by Step

by Robert
0 comments
How to Configure Csrf Step by Step

Why CSRF protection is essential

Cross-Site Request Forgery (CSRF) attacks let a malicious site trigger actions on behalf of a logged-in user against a trusted site. Without CSRF protection, attackers can submit forms, change settings, or perform transactions simply by getting a user to visit a crafted page. Protecting state-changing endpoints is not optional; it’s a core part of secure web application design. The good news is that implementing CSRF protection follows well-understood patterns that fit most stacks, and once configured correctly it reduces a large class of attacks to near zero.

Core approaches to CSRF mitigation

There are a few reliable ways to stop CSRF. The most common is the synchronizer token pattern: generate a unique token per session and embed it in forms and ajax requests; the server validates the token on submission. Another approach is the double-submit cookie: place a CSRF token in a cookie and echo it in a header or form value, comparing the two on the server. Cookies set with SameSite=strict or lax also block many cross-site requests for modern browsers; combine this with tokens for stronger protection. For APIs used across origins, enforce cors and require authorization headers rather than relying on cookies.

Step-by-step configuration (general)

The following steps show a reliable path to add CSRF protection to an existing application. Each step explains what to change and why. You can adapt the pattern to your framework or language.

  1. Identify state-changing endpoints: List POST, PUT, PATCH, DELETE endpoints and any GET endpoints that perform state changes (GET should be idempotent; if not, change it). Only requests that change state actually need CSRF protection.
  2. Choose a token strategy: Use a server-generated synchronizer token on pages and forms. For single-page apps, have the server provide a token endpoint and require the token in a custom header (for example X-CSRF-Token).
  3. Store the token server-side: Keep the token tied to the user session (session store, signed cookie, or secure storage). Tokens should be unpredictable cryptographically and rotated periodically or per login.
  4. Emit the token to the client: Embed the token in server-rendered forms as a hidden field, or place it in a response header or a json endpoint for SPA consumption. Avoid exposing tokens in urls.
  5. Require token on submission: Validate the token for every protected request. Reject requests with missing or invalid tokens with a 403 status and a clear diagnostic log entry.
  6. Harden cookies: Set cookies to Secure and HttpOnly where appropriate, and prefer SameSite=lax/strict for authentication cookies. For cross-origin APIs, prefer token-based auth in Authorization headers rather than cookie-based sessions.
  7. Test and monitor: Use automated tests, manual checks with curl or browser devtools, and monitoring to detect repeated 403 patterns or bypass attempts.

Example: server-rendered synchronizer token

A simple server-rendered flow generates a per-session token and embeds it into html forms. The server stores the token in the session and checks it during POST handling. This is straightforward and works well with classic web apps that use server-side templates.


// Pseudocode server-side
session.csrfToken = generateSecureRandom();
renderForm("name='csrf' value='" + session.csrfToken + "'/>");
// On POST
if (request.form.csrf != session.csrfToken) rejectWith403();

Example: single-page app (SPA) flow

For SPAs, the server exposes a CSRF token endpoint or issues a cookie. The client reads the token and sends it in an HTTP header for any state-changing AJAX requests. Servers then validate header value against the stored token. Ensure the token is not accessible via url and is rotated on logout/login.


// Client fetches token
GET /csrf-token -> { "csrfToken": "abc123" }
fetch('/api/update', {
method: 'POST',
headers: { 'X-CSRF-Token': csrfToken, 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});

Framework-specific quick configurations

Many frameworks provide built-in CSRF mechanisms; prefer the framework feature because it integrates with sessions, template engines, and default cookie settings. Below are concise examples for common stacks so you can follow a pattern quickly.

Spring Security (Java)

Spring Security enables CSRF protection by default for web applications. To use it with forms and AJAX, include the CSRF token in your templates using the provided tag or in headers. For APIs that use stateless JWTs, disable CSRF because tokens in headers are not vulnerable to CSRF the same way cookies are.


// Java config (simplified)
http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
// Template: include _csrf.token in a hidden field or read header name and token for AJAX

Django (Python)

Django has middleware that enforces CSRF tokens for POST requests. Ensure you include {% csrf_token %} in any template form and configure AJAX by reading the csrftoken cookie and setting it in an X-CSRFToken header.


// In template:
{% csrf_token %} ...

// In JavaScript for AJAX:
headers['X-CSRFToken'] = getCookie('csrftoken');

Express (Node.js) with csurf

The csurf middleware implements the synchronizer token pattern. Add it after your session middleware, expose the token to templates or an API route, and verify it on state-changing routes. For JSON APIs with token-based auth, prefer header-based authorization.


const csurf = require('csurf');
app.use(session({...}));
app.use(csurf());
app.use((req, res, next) => {
res.locals.csrfToken = req.csrfToken();
next();
});

Angular / Front-end frameworks

Many front-end frameworks and tooling support reading a cookie-supplied token and automatically sending it as a header (Angular’s XSRF support is one example). Configure your backend to accept that header and validate it against the session. For token-based APIs using OAuth or JWT, require Authorization headers and protect CORS instead of CSRF tokens.

Testing and verification

After configuration, verify protection works by attempting a cross-site submission and confirming the server rejects it. Use curl to simulate missing token and expect a 403. Check that legitimate flows with correct tokens succeed and that tokens are single-use or rotate based on your policy. In browser devtools, ensure the CSRF token is present in forms or request headers and that cookies are set with Secure and SameSite attributes where appropriate.

  • Manual test: submit a form without the token and observe 403.
  • Automated test: include token extraction and validated request in integration tests.
  • Penetration test: simulate cross-site forms and see if any endpoint accepts them.

Common pitfalls and what to avoid

A few mistakes commonly undermine CSRF defenses. First, don’t place tokens in URLs,query strings are logged and can leak. Second, don’t rely solely on SameSite for older browser coverage or complex cross-origin workflows; use token validation where sessions and cookies are involved. Third, avoid disabling CSRF globally for convenience; restrict exceptions to documented endpoints that use strong alternative protections such as header-based token auth. Finally, when using CORS, do not allow credentials from arbitrary origins; specify allowed origins explicitly and require a CSRF token for any cookie-backed session.

How to Configure Csrf Step by Step

How to Configure Csrf Step by Step
Why CSRF protection is essential Cross-Site Request Forgery (CSRF) attacks let a malicious site trigger actions on behalf of a logged-in user against a trusted site. Without CSRF protection, attackers…
AI

Summary

Configuring CSRF protection means choosing a reliable token strategy, integrating it with your session or authentication model, emitting tokens to clients safely, and validating tokens on state-changing requests. Use built-in framework features where available, harden cookies with appropriate flags, and verify with tests. With these steps in place you prevent forged cross-site requests and keep user actions confined to the intended origin.

FAQs

Do I need CSRF protection for APIs that use JWTs?

If your API uses JWTs sent in Authorization headers (Bearer tokens), CSRF risk is minimal because headers cannot be set by a third-party site in a simple cross-site form submission. However, if you store JWTs in cookies and rely on cookie-based authentication, you still need CSRF protection. Prefer Authorization headers for APIs and enforce CORS.

Is SameSite cookie enough to stop CSRF?

SameSite provides strong protection for many scenarios and is a useful default, but it doesn’t cover all cases, especially older browsers or complex cross-site integrations. Combine SameSite with token validation for robust protection when sessions are stored in cookies.

How often should CSRF tokens be rotated?

Rotate tokens on user login/logout and consider periodic rotation for long-lived sessions. Per-request rotation increases security but adds complexity; per-session tokens are a common and practical balance.

What about AJAX requests and single-page apps?

For SPAs, expose a CSRF token via a secure endpoint or cookie and require that clients send it in a custom header (e.g., X-CSRF-Token). Verify that header on the server and keep tokens out of URLs.

How to debug CSRF errors in production?

Log token validation failures with enough context to diagnose (user id, session id, request path) without exposing tokens in logs. Reproduce the failing request locally with curl or Postman, check headers and cookies in the browser’s network tab, and confirm token issuance and session linkage.

You may also like