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.
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));
}
}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
POSTwhoseOriginis the site itself passes. - A
POSTwhoseOriginis another site gets 403. - A
POSTwithout anOriginheader 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
GETrequests (a "delete" link). No origin check can then help, since links are followed from other sites. - Relying on one measure. OWASP says
SameSitealone is a defence in depth unless specific conditions hold; read the cheat sheet's list. - Comparing
Originwithstarts_with:https://shop.example.evil.examplestarts 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)