# How do I add CSRF protection to a Rust web application?
Source: https://ruststudio.org/community/t/91/how-do-i-add-csrf-protection-to-a-rust-web-application
Author: Ruststudio Team (staff) | Published: 2026-12-05 | Updated: 2026-12-05 | Checked with: rustc 1.93.0, hmac 0.12.1, sha2 0.10.9, hex 0.4.3, getrandom 0.2.17, Windows 11
Category: Help and questions | Kind: FAQ | Tags: security, csrf, web, hmac | Views: 0

## Short answer
Require an unpredictable token on every request that changes data, tie it to the session so a token from one session is useless in another, and check it in constant time. Combine it with SameSite cookies and, for browser APIs, checks of the Origin header. Safe methods such as GET must never change state.

## Answer
## Answer
Cross-site request forgery works because browsers attach your cookies to requests that another site triggers. A hostile page can make the browser send `POST /transfer` with the user's session cookie. The server cannot tell it from a genuine form submission, **unless** the genuine form includes something the hostile page cannot know.

That something is a token. The OWASP CSRF cheat sheet describes a signed, session-bound variant: the token is a random nonce plus an HMAC of the session ID and the nonce under a server-side key. The server needs no table of issued tokens; it recomputes the tag.

```rust title=src/main.rs
use hmac::{Hmac, Mac};
use sha2::Sha256;

type HmacSha256 = Hmac<Sha256>;

fn mac(key: &[u8], session_id: &str, nonce: &[u8]) -> HmacSha256 {
    let mut m = HmacSha256::new_from_slice(key).unwrap();
    m.update(session_id.as_bytes());
    m.update(b"|");
    m.update(nonce);
    m
}

/// A token tied to one session: "nonce.tag", both hex.
fn make_token(key: &[u8], session_id: &str) -> String {
    let mut nonce = [0u8; 16];
    getrandom::getrandom(&mut nonce).unwrap();
    let tag = mac(key, session_id, &nonce).finalize().into_bytes();
    format!("{}.{}", hex::encode(nonce), hex::encode(tag))
}

fn check_token(key: &[u8], session_id: &str, token: &str) -> bool {
    let Some((n, t)) = token.split_once('.') else { return false };
    let (Ok(nonce), Ok(tag)) = (hex::decode(n), hex::decode(t)) else { return false };
    mac(key, session_id, &nonce).verify_slice(&tag).is_ok() // constant-time comparison
}

fn main() {
    let key = b"server-side signing key, 32+ bytes long!";
    let token = make_token(key, "session-A");
    println!("same session:      {}", check_token(key, "session-A", &token));
    println!("another session:   {}", check_token(key, "session-B", &token));
    println!("damaged token:     {}", check_token(key, "session-A", "00.00"));
    println!("no token at all:   {}", check_token(key, "session-A", ""));
}
```

```text
same session:      true
another session:   false
damaged token:     false
no token at all:   false
```

The key comes from your secrets (see the thread on secrets); the literal in `main` is for the demonstration only.

## How to do it
1. Put a fresh token into every HTML form as a hidden field, and into the page for scripts that send requests.
2. For every `POST`, `PUT`, `PATCH` and `DELETE`, reject the request when the token is missing or wrong (HTTP 403).
3. Never change state on `GET`.
4. Set session cookies with `SameSite=Lax` or `Strict` (see the thread on cookie attributes). This is a strong second layer, not a replacement for tokens, because browsers differ and same-site attacks exist.
5. For requests from scripts you can additionally check that the `Origin` header matches your site.
6. Do not accept the token from cookies alone: a double-submit scheme needs a signed value, as above, to be safe.

## Common mistakes
- Using the same token for every user and every day.
- Exempting "internal" or JSON endpoints. Browsers can send JSON-looking bodies cross-site in some situations; protect them as well.
- Skipping the check on login or on logout.
- Leaking the token in a URL (for example, `?csrf=...`), where it can reach logs and `Referer` headers.

## Related questions
### Do I need CSRF tokens if the API uses a bearer token in a header, not a cookie?
A browser does not add that header by itself, so the classic forgery does not apply. The risk returns as soon as authentication moves to cookies.

### Where does the token go for a JavaScript front end?
Send it in a custom request header (for example `X-CSRF-Token`) that your own script adds. Browsers do not add custom headers on forms from other sites.

## Sources
- OWASP Cross-Site Request Forgery Prevention Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html
- `hmac` documentation: https://docs.rs/hmac/0.12.1/hmac/
