Tuesday, November 11, 2025

Top 5 Popular Articles

cards
Powered by paypal
Infinity Domain Hosting

Related TOPICS

ARCHIVES

What Is Csrf and How It Works in Website Security

What is CSRF (Cross-Site Request Forgery)?

Cross-Site Request Forgery, commonly called CSRF, is an attack that tricks a web browser into making an unwanted request to a site where the user is already authenticated. The browser automatically includes credentials such as cookies or HTTP authentication headers, so the target site sees the request as coming from the legitimate user. An attacker uses this behavior to perform actions on the victim’s behalf,changing account settings, transferring funds, or posting content,without the user’s knowledge.

How CSRF actually works

The key reason CSRF is possible is that browsers automatically attach session cookies and certain authentication headers to matching domains. Imagine a user logged into bank.example.com. While signed in, they visit a malicious page (attacker.example) or view an email containing a crafted link or hidden form. That page can cause the browser to issue a request to bank.example.com,for example, a POST that transfers money,and the browser will include the bank’s session cookie. The bank’s server sees a valid session and executes the operation, believing the authenticated user requested it.

Common ways attackers trigger these requests include simple html forms, image tags (for GET requests), and auto-submitting forms. Modern browsers block cross-origin JavaScript from reading responses, but they do not prevent the browser from sending authenticated requests, which is exactly what CSRF relies on.

Typical attack patterns

  • HTML form submission: an attacker builds a hidden form that posts to a banking endpoint and auto-submits it with JavaScript.
  • Image or link-based GET: an <img src=" tag makes a GET request; if the endpoint performs state change, the action completes.
  • Cross-origin POST via form: because forms can target other domains, an attacker can submit POST requests without needing cors.
  • Script-injection scenarios: if an attacker can inject JavaScript (XSS), they can perform CSRF-like actions too, but XSS is a different, more powerful issue.

Why Same-Origin Policy doesn’t stop CSRF

The Same-Origin Policy prevents scripts on one origin from reading data from another origin, but it does not stop the browser from sending requests across origins. That asymmetry is by design: images, stylesheets, and forms must be able to load resources across origins. Because credentials like cookies are sent automatically when the request matches the target domain, an attacker can cause the request but cannot read the result. The server, however, cannot distinguish between a legitimate request initiated by the user and a forged request initiated by a third-party page unless the server implements protections.

Effective defenses and how they work

Mitigations aim to ensure that state-changing requests are genuinely initiated by the user and by the site’s pages. You should treat any request that changes data as untrusted unless accompanied by a proof of intent that an attacker can’t reproduce from another origin. Below are the most widely used defenses and what they do.

CSRF tokens (synchronizer tokens)

A server-generated token is embedded in HTML forms or pages and validated on submission. The token is unique to the user’s session (or per-request) and stored server-side. Because an attacker on another domain can’t read the token, they cannot include it in a forged request. Tokens are simple to implement and work with standard browser flows; most web frameworks provide built-in CSRF token support.

Double-submit cookie

The server sends a cookie containing a random value and the client JavaScript copies that value into a request header or form field for each sensitive request. The server compares the cookie value to the submitted value. This method avoids server-side storage of tokens but requires the ability to run same-origin JavaScript to copy the cookie value into the request; it also relies on cookies being readable by JavaScript (so flags like HttpOnly must be considered).

SameSite cookie attribute

Modern browsers support the SameSite attribute on cookies. When set to Lax or Strict, the browser restricts sending cookies on cross-site requests. Lax prevents cookies on many cross-site requests but allows top-level navigations for safe methods, while Strict blocks more aggressively. SameSite is a powerful mitigation for many CSRF scenarios, especially combined with other controls. Note that legacy browsers or improperly configured cookies can weaken its effect.

Origin and Referer header checks

For requests that modify state, the server can check the Origin or Referer header to confirm the request comes from an allowed origin. The Origin header is preferred for POST/PUT/DELETE requests because it reliably indicates the initiating origin for CORS-style requests. This check is straightforward for APIs and form submissions, but it fails when proxies or privacy settings strip those headers.

Use tokens in headers for APIs

If your API requires an Authorization header or a custom header, then browsers will not allow cross-origin JavaScript to send those headers without CORS preflight. This prevents a simple CSRF because an attacker cannot craft a cross-origin request that includes custom headers without the server explicitly allowing it via CORS. Single-page applications commonly store a bearer token (not a cookie) and attach it as a header; combined with proper token storage and CORS, this avoids cookie-based CSRF.

Additional hardening

  • Require re-authentication or multi-factor confirmation for high-value actions (changing email, transfers).
  • Make state-changing endpoints idempotent where possible, and avoid performing sensitive actions on GET requests.
  • Set cookies with Secure and HttpOnly flags when appropriate, and use SameSite with a reasonable policy.
  • Keep libraries and frameworks updated to benefit from built-in CSRF protections.

Practical examples

A minimal attack example: an attacker hosts a page that auto-submits a form to with fields populated. If the victim is logged in to example.com, the browser will send the session cookie and the email address will be changed. The simplest server-side fix is to require a CSRF token to be included and verified for any non-idempotent endpoint.

<!-- Attacker's page -->
<form action="" method="POST" id="f">
<input type="hidden" name="email" value="attacker@example.com">
</form>
<script>document.getElementById('f').submit();</script>

A defensive example: server renders a token into the form and validates it on POST. Only pages served by example.com can read that token, so attacker.example cannot include it in their forged request.

Where CSRF matters most

CSRF primarily concerns sites that rely on browser-managed credentials like cookies. Traditional web applications, banking sites, admin panels, and any web UI where a logged-in user can change server-side state are high risk. Single-page applications that use tokens stored in local storage and attach them as headers are less susceptible to classic CSRF, but they must avoid storing sensitive tokens in insecure places and should still use server-side checks for critical actions.

What Is Csrf and How It Works in Website Security

What Is Csrf and How It Works in Website Security
What is CSRF (Cross-Site Request Forgery)? Cross-Site Request Forgery, commonly called CSRF, is an attack that tricks a web browser into making an unwanted request to a site where the…
AI

Developer checklist to prevent CSRF

  • Enable framework-provided CSRF protection for forms and state-changing endpoints.
  • Set SameSite cookies (Lax or Strict) along with Secure and HttpOnly as suitable.
  • Reject state-changing requests with missing or invalid CSRF tokens or wrong Origin/Referer headers.
  • Avoid performing state changes on GET requests.
  • Require elevated authentication for high-risk operations.

Summary

CSRF is a real risk whenever browsers automatically attach credentials like cookies to requests. The attack tricks a user’s browser into submitting a request the user did not intend. Preventing CSRF relies on adding proofs of intent,CSRF tokens, SameSite cookie policies, Origin checks, and careful API design. Combining these controls with secure cookie attributes and re-authentication for sensitive actions creates robust protection for web applications.

FAQs

Is CSRF the same as XSS?

No. Cross-Site Scripting (XSS) injects malicious script into a site and lets an attacker execute code in the victim’s context, which can be used to steal data or perform actions. CSRF forges requests from a user’s browser without reading responses. XSS is typically more powerful because it gives direct control, but both are serious and need separate defenses.

Can SameSite cookies completely eliminate CSRF?

SameSite significantly reduces many CSRF risks by stopping cookies on many cross-site requests, but it is not a complete substitute for tokens and other server-side checks. Older browsers may not support SameSite, and some flows intentionally require cross-site navigation. Use SameSite as part of a layered defense.

Are GET requests vulnerable to CSRF?

They can be, which is why best practice dictates that GET requests should never perform state changes. Treat GET as safe and idempotent; use POST/PUT/DELETE for state changes and protect those with CSRF defenses.

How should APIs be protected against CSRF?

For APIs that use cookie-based authentication, apply CSRF tokens or SameSite cookie settings and check Origin/Referer headers. For token-based APIs, require the token be sent in an Authorization header; browsers won’t let a third-party page send that header without CORS permission, which prevents classic CSRF.

What if I use a framework,do I still need to worry about CSRF?

Many frameworks include CSRF protection by default, but you still need to understand and correctly configure it, ensure it’s applied to all state-changing endpoints, and complement it with secure cookie flags and SameSite policies. Always test sensitive flows and confirm protections are active.

Recent Articles

Infinity Domain Hosting Uganda | Turbocharge Your Website with LiteSpeed!
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.