Skip to main content

Module csrf

Module csrf 

Source
Available on crate feature 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

  1. On safe methods (GET/HEAD/OPTIONS): CsrfLayer reads the existing _csrf cookie or generates a 32-byte random token. The token is injected into the request (as an internal header) so CsrfToken::from_request can return it to the handler. The cookie is (re-)set on the response.

  2. On mutating methods: the layer reads the cookie value and the submitted value (from the X-CSRF-Token header or the _csrf form field). It compares them in constant time and returns 403 Forbidden if they do not match.

Structs§

CsrfLayer
CSRF protection middleware.
CsrfToken
The CSRF token for the current request.