# How do I add a cross-site request check (CSRF defence) to an axum app?
Source: https://ruststudio.org/community/t/174/how-do-i-add-a-cross-site-request-check-csrf-defence-to-an-axum-app
Author: Ruststudio Team (staff) | Published: 2026-12-05 | Updated: 2026-12-05 | Checked with: rustc 1.93.0, axum 0.8.9, tokio 1.54.1, tower 0.5.3, Windows 11; handlers called in-process with tower's oneshot
Category: Help and questions | Kind: FAQ | Tags: axum, csrf, security, middleware | Views: 0

## Short answer
Browsers attach cookies to requests that another site triggers, so a forged form post can act as the logged-in user. Use SameSite cookies and a CSRF token on state-changing requests; as an extra layer, refuse unsafe methods whose Origin header names another site, as in the middleware below.

## Answer
## Answer
Cross-site request forgery works because a browser sends your site's cookies even when the request was started by a page on another site. The OWASP cheat sheet recommends **tokens** (the synchronizer token pattern) as the main defence, with `SameSite` cookies and checks of the `Origin` header as additional layers. This thread shows the `Origin` layer only; it is not a complete defence on its own.

```rust title=src/main.rs
use axum::{
    body::{to_bytes, Body},
    extract::Request,
    http::{header, Method, StatusCode},
    middleware::{self, Next},
    response::Response,
    routing::{get, post},
    Router,
};
use tower::ServiceExt;

const SITE: &str = "https://shop.example";

/// Refuse state-changing requests that a browser says came from another site.
async fn same_origin_only(req: Request, next: Next) -> Result<Response, StatusCode> {
    let safe = matches!(*req.method(), Method::GET | Method::HEAD | Method::OPTIONS);
    if !safe {
        if let Some(origin) = req.headers().get(header::ORIGIN) {
            if origin.as_bytes() != SITE.as_bytes() {
                return Err(StatusCode::FORBIDDEN);
            }
        }
    }
    Ok(next.run(req).await)
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(|| async { "page" }))
        .route("/delete-account", post(|| async { "deleted" }))
        .layer(middleware::from_fn(same_origin_only));
    for (method, uri, origin) in [
        ("GET", "/", Some("https://evil.example")),
        ("POST", "/delete-account", Some("https://shop.example")),
        ("POST", "/delete-account", Some("https://evil.example")),
        ("POST", "/delete-account", None),
    ] {
        let mut b = Request::builder().method(method).uri(uri);
        if let Some(o) = origin { b = b.header(header::ORIGIN, o); }
        let res = app.clone().oneshot(b.body(Body::empty()).unwrap()).await.unwrap();
        let status = res.status().as_u16();
        let body = to_bytes(res.into_body(), usize::MAX).await.unwrap();
        println!("{method} {uri} Origin={origin:?} -> {status} {:?}", String::from_utf8_lossy(&body));
    }
}
```

```text
GET / Origin=Some("https://evil.example") -> 200 "page"
POST /delete-account Origin=Some("https://shop.example") -> 200 "deleted"
POST /delete-account Origin=Some("https://evil.example") -> 403 ""
POST /delete-account Origin=None -> 200 "deleted"
```

- Safe methods (`GET`, `HEAD`, `OPTIONS`) pass: they must never change data.
- A `POST` whose `Origin` is the site itself passes.
- A `POST` whose `Origin` is another site gets 403.
- A `POST` **without** an `Origin` header passed. This middleware chooses to allow it, because non-browser clients (scripts, curl) do not send one. That is a trade-off: a stricter site may want to require a token as well, which this thread does not show.

## Common mistakes
- Changing data on `GET` requests (a "delete" link). No origin check can then help, since links are followed from other sites.
- Relying on one measure. OWASP says `SameSite` alone is a defence in depth unless specific conditions hold; read the cheat sheet's list.
- Comparing `Origin` with `starts_with`: `https://shop.example.evil.example` starts with the site's name. Compare the whole value, as the code does.

## Related questions
### Where does the token go?
Generate a random token per session, store it server-side, put it in a hidden form field, and compare it on every unsafe request. The OWASP page describes the patterns in detail; this thread did not compile token code.

### Does CORS stop CSRF?
No. CORS controls which pages may *read* responses; a forged form post is sent regardless (see the CORS thread).

## Sources
- OWASP CSRF Prevention Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html (read 2026-12-05)
