Skip to content
uencoder
TASK

Prevent CSRF (Cross-Site Request Forgery) attacks

CSRF tricks authenticated users into submitting unwanted requests. Learn anti-CSRF tokens, SameSite cookies, and double-submit patterns.

  1. 1

    CSRF exploits the browser's automatic sending of cookies. If a user is logged in (cookies present) and visits a malicious site, that site can submit a form to the target site — the cookies are sent automatically. Prevention: (1) Anti-CSRF tokens (synchronizer pattern) — a random token in the form and session, verified on submission. (2) SameSite cookies — cookies are not sent cross-site. (3) Origin/Referer header validation. (4) Require custom headers for state-changing requests.

  2. 2
    HMAC Generator →

    Generate an anti-CSRF token. The token should be: unpredictable (CSPRNG), per-session (or per-request for higher security), and bound to the user's session. HMAC(session_id, random) is a common pattern — it is deterministic (same session → same token) but unforgeable without the secret.

  3. 3
    Hash Calculator →

    For the double-submit pattern: generate a random token, set it as a cookie (not HttpOnly, so JavaScript can read it) and include it as a header in every request. The server verifies that the cookie and header match. This does not require server-side state. Use SHA-256 for the token hash.

Frequently asked questions

Are SameSite cookies enough to prevent CSRF?
SameSite=Lax (default in modern browsers) prevents CSRF for top-level navigations (form POST, link clicks) but allows GET requests. SameSite=Strict prevents all cross-site sending but breaks legitimate cross-site usage (e.g., following a link to your site from email). Use SameSite=Lax + CSRF tokens for defense in depth.
CSRF vs XSS — what is the difference?
XSS executes malicious code in the victim's browser (the attacker reads data or performs actions as the user). CSRF tricks the victim's browser into making a request to a site where they are authenticated (the attacker does not read the response). XSS is a code injection; CSRF is a request forgery. XSS can bypass CSRF protections (the script can read the token).

Workflows that solve this

Learn more

Want to understand why?

Related tools