Expand description
CSRF protection for cookie-authenticated forms and APIs
Csrf needs the SessionLayer before it.
Every request with an unsafe method (POST, PUT, PATCH, DELETE) must
prove it was made by your own pages in two ways:
- Origin check: an
Originheader (or, without it,Sec-Fetch-Site) that points to another site is rejected with403. - Token: the session’s token, sent as the
x-csrf-tokenheader or as thecsrf_tokenfield of an urlencoded or multipart form. Compared in constant time.
use ullun::csrf::Csrf;
use ullun::prelude::*;
use ullun::session::SessionLayer;
App::new()
.middleware(SessionLayer::new())
.middleware(Csrf::new())
.get("/form", |req: Request| async move {
let token = req.session()?.csrf_token()?;
Ok(Response::html(format!(
r#"<form method="post" action="/save"><input type="hidden" name="csrf_token" value="{token}"><button>Save</button></form>"#
)))
})
.post("/save", |_req: Request| async { Ok(Response::text("saved")) })
.run("127.0.0.1:3000")
.await
.unwrap();Scripts read the token from a <meta> tag you render and send it as a
header. Requests that authenticate with an Authorization header instead of
cookies are not CSRF-prone: exempt them with Csrf::exempt.
Structs§
- Csrf
- CSRF middleware, see the module docs