csrf only.Expand description
CSRF protection middleware using the double-submit cookie pattern.
Enabled by the csrf Cargo feature:
rust-web-server = { version = "17", features = ["csrf"] }§Usage
Add CsrfLayer to the middleware stack. It validates the CSRF token on
every mutating request (POST, PUT, PATCH, DELETE) and passes safe
methods through unconditionally.
use rust_web_server::app::App;
use rust_web_server::core::New;
use rust_web_server::csrf::CsrfLayer;
let app = App::new().wrap(CsrfLayer::new());§Embedding the token in HTML forms
In a GET handler, call CsrfToken::from_request to obtain the current
token and embed it in the form:
use rust_web_server::core::New;
use rust_web_server::csrf::CsrfToken;
use rust_web_server::request::Request;
use rust_web_server::response::Response;
use rust_web_server::server::ConnectionInfo;
fn show_form(req: &Request, _conn: &ConnectionInfo) -> Response {
let token = CsrfToken::from_request(req)
.map(|t| t.value().to_string())
.unwrap_or_default();
let html = format!(
r#"<form method="POST" action="/submit">
<input type="hidden" name="_csrf" value="{token}">
<button type="submit">Submit</button>
</form>"#
);
Response::new() // build your response with `html` body
}For AJAX, include the token in the X-CSRF-Token request header. The cookie
is not HttpOnly by default so that JavaScript can read it via
document.cookie; call .http_only(true) to
restrict to HTML-form workflows only.
§How it works
-
On safe methods (
GET/HEAD/OPTIONS):CsrfLayerreads the existing_csrfcookie or generates a 32-byte random token. The token is injected into the request (as an internal header) soCsrfToken::from_requestcan return it to the handler. The cookie is (re-)set on the response. -
On mutating methods: the layer reads the cookie value and the submitted value (from the
X-CSRF-Tokenheader or the_csrfform field). It compares them in constant time and returns403 Forbiddenif they do not match.