Square CloudSquare Cloud

What is CSRF and how to protect your forms and APIs

CSRF (cross-site request forgery) is an attack where another site makes the victim's browser send your site a request carrying their cookies. The defense is your framework's protection or an anti-CSRF token; in current browsers, a Sec-Fetch-Site check with an Origin fallback also works, and SameSite is an extra layer.

Updated 8 min read

Learning objectives

After reading this article you will be able to:

  • Understand why cookies make CSRF possible
  • Protect forms with synchronizer tokens, SameSite and Origin checks
  • Know when an API using Authorization: Bearer does not need an anti-CSRF token
On this page

You sign in to your bank's site, do what you need and leave the tab open. Later, you open some link on a forum. That page has an invisible form that sends a POST to the bank asking for a transfer and, unless the cookie restricts it, your browser sends the session cookie along. The bank sees an authenticated request and runs it.

That is CSRF. The attacker never sees your password or your cookie: they only exploit the fact that the browser sends them on its own.

What is CSRF?#

Cross-site request forgery (CSRF) is an attack where a page the attacker controls makes a signed-in user's browser send a request that changes state on your site: changing the email, moving money, deleting a resource. MDN sums up the risk condition: a site is exposed when it uses only cookies to know that a request came from an authenticated user.

The attack is blind. The same-origin policy stops the attacker's page from reading the response, so CSRF targets actions, not data. One action is enough: changing the account's email and then requesting a password reset hands over the whole account.

Why do cookies make CSRF possible?#

The browser attaches a cookie to every request for the domain that set it, no matter which page triggered the request. A form, an <img> tag or a fetch from another site carry the cookie along unless the SameSite attribute says otherwise. The attacker's page only needs this:

html
<!-- attacker's page -->
<form action="https://bank.example/transfer" method="POST" id="f">
  <input type="hidden" name="to" value="attacker-account">
  <input type="hidden" name="amount" value="1000">
</form>
<script>document.getElementById("f").submit();</script>

With GET it is even simpler: <img src="https://bank.example/transfer?to=attacker&amount=1000"> fires the request as soon as the page loads. The first rule, repeated by OWASP and MDN, is never to change state with GET.

And CORS does not help. An HTML form sends a POST with application/x-www-form-urlencoded, which MDN classifies as a simple request: it goes out with no preflight, and the server receives and runs it. CORS only decides whether the other site's JavaScript can read the response. With a simple request sent by fetch, the CORS error shows up in the console after the server has already processed the request.

How does SameSite protect cookies?#

SameSite is a cookie attribute that tells the browser whether to send the cookie on requests started by another site.

Value When the cookie is sent Effect on CSRF
Strict Only on same-site requests Blocks it, but someone arriving from an outside link shows up signed out
Lax Same site, plus top-level navigations with a safe method (clicking a link) Blocks cross-site POST; a GET navigation still carries the cookie
None Always (requires Secure) No protection

When a cookie does not declare SameSite, the result depends on the browser. Chrome treats that cookie as Lax, but MDN only says that "some browsers" do this, and that default Lax is more permissive: the cookie still goes on a cross-site POST if it was set no more than two minutes earlier. Do not rely on the default; declare the value:

http
Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=Lax; Path=/

Even when declared, SameSite has limits that OWASP lists. Lax sends the cookie on GET navigations from other sites, so a route that changes state with GET stays exposed, and MDN notes that frameworks with "method override" let a GET pass as a POST. And "site" means the registrable domain: blog.example.com and app.example.com are the same site, so a compromised subdomain gets through. The same goes for the address a host gives each customer (yourapp.platform.app): neighboring apps only count as another site if the platform's domain is on the Public Suffix List. That is why SameSite is defense in depth, not the main defense.

How does an anti-CSRF token work?#

A synchronizer token is a random value the server generates, stores in the session and puts in the form. Every state-changing request must send the token back, and the server compares it with the one in the session. The attacker's page cannot read yours to learn the value, so it cannot forge the request.

An example with Express and express-session:

js
import { randomBytes, timingSafeEqual } from "node:crypto";
import express from "express";
import session from "express-session";

const app = express();
app.set("trust proxy", 1); // behind a proxy that terminates HTTPS
app.use(express.urlencoded({ extended: false }));
app.use(
  session({
    secret: process.env.SESSION_SECRET,
    resave: false,
    saveUninitialized: false,
    cookie: {
      httpOnly: true,
      secure: process.env.NODE_ENV === "production",
      sameSite: "lax",
    },
  }),
);

function sessionToken(req) {
  req.session.csrf ??= randomBytes(32).toString("hex");
  return req.session.csrf;
}

function requireToken(req, res, next) {
  const expected = Buffer.from(req.session.csrf ?? "");
  const received = Buffer.from(String(req.body?._csrf ?? req.get("X-CSRF-Token") ?? ""));
  const valid =
    expected.length > 0 &&
    expected.length === received.length &&
    timingSafeEqual(expected, received);
  if (!valid) return res.status(403).send("Invalid CSRF token");
  next();
}

app.get("/account/email", (req, res) => {
  res.send(`<form method="POST" action="/account/email">
  <input type="hidden" name="_csrf" value="${sessionToken(req)}">
  <input type="email" name="email" required>
  <button>Save</button>
</form>`);
});

app.post("/account/email", requireToken, (req, res) => {
  // the request came from one of your pages: update the email here
  res.send("Email updated");
});

app.listen(process.env.PORT ?? 3000);

The token goes in a hidden field or, for fetch calls, in a header such as X-CSRF-Token; OWASP considers the header more secure and says the token should never go in the URL. In production, replace express-session's default MemoryStore with a persistent store (Redis, for example): its docs say it was not designed for production. The same docs warn that with secure, the cookie is not set on a request the app sees as HTTP; behind a proxy that terminates HTTPS, trust proxy makes Express read the protocol the proxy reports in X-Forwarded-Proto. Check the headers that actually arrive before relying on it.

Full-stack frameworks ship this turned on. In Django, the CSRF middleware is active by default and the form includes {% csrf_token %}. In Laravel, the @csrf directive renders the field, and the docs describe a Sec-Fetch-Site check that falls back to the token when the header is missing. Your job is not to turn the protection off.

To avoid server-side state, there is the double submit pattern: the server sends the token in a cookie and the client repeats it in a header or field. OWASP discourages the naive version, which only compares the two, because anyone who can write cookies on your domain (through a vulnerable subdomain, for example) can plant a matching pair. The recommended version signs the token with an HMAC and binds it to the user's session.

How do you check Origin and Sec-Fetch-Site?#

Current browsers send headers that say where a request came from, and a page's JavaScript cannot change them. Sec-Fetch-Site says whether the request is same-origin, same-site, cross-site or none (started by the user, such as a bookmark), and the browser only sends it over HTTPS (and on localhost). Origin carries the scheme, host and port of the page that sent the request.

js
const APP_ORIGIN = process.env.APP_ORIGIN; // e.g. https://app.example.com
const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);

function sameOrigin(req, res, next) {
  if (SAFE_METHODS.has(req.method)) return next();

  const site = req.get("Sec-Fetch-Site");
  if (site) {
    return site === "same-origin" ? next() : res.status(403).send("Origin rejected");
  }
  // browser without Fetch Metadata: check Origin
  if (req.get("Origin") === APP_ORIGIN) return next();
  return res.status(403).send("Origin rejected");
}

app.use(sameOrigin);

OWASP's rules for this check: compare the whole origin with exact equality (a prefix test would let https://app.example.com.attacker.net through); on sensitive routes, treat a missing header or Origin: null as a rejection, never as proof of same origin; and keep the Origin fallback, which OWASP calls mandatory, because older browsers do not send Sec-Fetch-Site. Proxies and load balancers can strip these headers, so start by only logging rejections, without blocking, until you have found the false positives. Clients outside the browser, such as curl or another server, send neither header: if the same route serves both, apply the check only to cookie-authenticated requests.

Defense Keeps state? Notes
Synchronizer token Yes, in the session The most proven; frameworks ship it
Signed double submit No Needs an HMAC bound to the session
Sec-Fetch-Site with Origin fallback No HTTPS only; the Origin fallback is mandatory
SameSite No Extra layer, not the main one

Is an API using Authorization: Bearer vulnerable to CSRF?#

CSRF depends on credentials the browser attaches on its own. The WHATWG Fetch standard lists three: cookies, TLS client certificates and HTTP authentication (such as Basic credentials entered in the browser's own dialog). A token your JavaScript puts in the Authorization: Bearer header is none of them. To forge the request, the attacker's page would need the token, and the same-origin policy stops it from reading your site's storage. On top of that, MDN notes that a request with a header outside CORS's safelist (Authorization is one) only goes to another origin if the server approves the preflight.

Three situations bring the risk back:

  • The token travels in a cookie, or the API also accepts a cookie. A JWT in an HttpOnly cookie is an automatic credential like any session, and an API that takes either cookie or header lets the attacker use the cookie. See JWT vs sessions.
  • The authentication is already automatic, such as HTTP Basic through the browser's dialog or a client certificate.
  • CORS allows other origins with credentials, on an API that accepts cookies. MDN puts it this way: a site is exposed to CSRF from an origin when its response to a state-changing request lists that origin in Access-Control-Allow-Origin and includes Access-Control-Allow-Credentials. Echoing back whatever Origin arrives opens the door to all of them.

The reverse holds too: a token in localStorage escapes CSRF but sits within reach of any XSS. And OWASP warns that XSS defeats every CSRF defense, because the script runs on your origin and reads the token from the page. To separate who the user is from what they can do, see authentication vs authorization.

How to do this on Square Cloud#

Tokens, SameSite and Origin checks live in your application's code, because only your code knows which routes change state and which origin they should accept. The WAF included in every Square Cloud plan is a generic layer at the edge: a forged request is well formed and carries the victim's valid cookie, so CSRF protection is still yours to build.

Every published web application gets a *.squareweb.app subdomain with HTTPS, so the session cookie can carry Secure, and the headers your application sets pass through the proxy intact. Keep SESSION_SECRET and APP_ORIGIN in the application's environment variables; a change takes effect on the next restart.

If you use load balancing (the same custom domain on two or more applications, from the Standard plan), there is no sticky session: keep the session, and the token with it, in Redis or a database, as the example asks for production.

See runtimes, plans and limits on the API hosting page.

Infrastructure

L3/L4/L7 DDoS mitigation and a WAF on every plan

API hosting

FAQs

Does SameSite=Lax fix CSRF?

It helps a lot, but OWASP and MDN treat SameSite as defense in depth. Lax still sends the cookie on GET navigations from other sites and does not separate subdomains of the same domain. Add a token or an Origin check.

Does CORS protect against CSRF?

No. CORS controls who can read the response, not who can send the request. An HTML form on another site sends a simple POST with no preflight, and the server receives and runs it.

Does an API with a JWT in the Authorization header need CSRF protection?

If the API authenticates only through the `Authorization` header and the token is not in a cookie, the browser never attaches it on its own, so the classic attack does not work. If the token travels in a cookie, or the API also accepts a cookie session, it needs protection again.

Can a GET request be a CSRF target?

Yes, and it is the easiest case: an image tag with the URL fires the request as the page loads. That is why OWASP and MDN say never to change state with GET.

What is the difference between CSRF and XSS?

With CSRF, the attacker runs no code on your site: they only make the browser send a request. With XSS, the script runs inside your page and can read the anti-CSRF token, which is why XSS defeats that defense.

Next articleSecurity checklist for deploying a bot, site or APIA security checklist before you deploy a bot, site or API: secrets in environment variables, dependencies, HTTPS, headers, least privilege and logs.

More in Security

See all 24 articles