Expand description
§crissy
crissy is a middleware for axum that protects
(browser-facing) web resources from cross-site request forgery (CSRF) attacks.
§Usage
In short:
- Pick a
middlewareand layer it in - Extract
CsrfToken - Add
CsrfToken::expected_csrf_tokento your form - Call
CsrfToken::validatein your form handler
For example:
use axum::{
Form, Router,
response::{Html, IntoResponse},
routing::get,
};
use crissy::CsrfToken;
use serde::Deserialize;
use tokio::net::TcpListener;
let app = Router::<()>::new()
.route("/", get(route_index).post(route_post))
.layer(axum::middleware::from_fn(crissy::middleware::cookie));
// Run `app` as usual
async fn route_index(csrf: CsrfToken) -> impl IntoResponse {
Html(format!(
r#"<form method="POST">
<input type="hidden" name="csrf_token" value="{csrf}"/>
<button type="submit">Submit</button>
</form>"#,
csrf = csrf.expected_csrf_token,
))
}
#[derive(Deserialize)]
struct Body {
csrf_token: String,
}
async fn route_post(csrf: CsrfToken, body: Form<Body>) -> Result<impl IntoResponse, crissy::Error> {
csrf.validate(&body.csrf_token)?;
Ok("validation successful!")
}§Feature flags
crissy supports the following feature flags:
| Name | Default | Description |
|---|---|---|
cookie | Yes | middleware::cookie |
client_ip | No | middleware::client_ip |
full | No | Enables all feature flags. |
Modules§
- middleware
- Users must use exactly one middleware from this module, which is responsible for generating and maintaining the CSRF tokens.
Structs§
- Csrf
Token - The client’s active CSRF token.