A stateless CSRF middleware for tower.
🏄♂️ Overview
This crate uses the Double Submit Cookie Pattern to mitigate CSRF.
How it works
- Secret key: You provide a secret key used to sign CSRF tokens. This secret is secured by secstr and only in memory as plaintext during the signing and validating processes. For more information on managing your secret key, see OWASP's Cryptographic Storage Cheat Sheet).
- Token creation:
- We generate a message by combining a unique session identifier with a cryptographically secure random value (using the
randcrate). - We then create an signature using the secret key and the message.
- The token is formed by concatenating the signature and the message.
- We generate a message by combining a unique session identifier with a cryptographically secure random value (using the
- Token storage:
- The server sends the token to the client in two ways:
- As a cookie (handled by us).
- In the header of subsequent requests (handled by you).
- The server sends the token to the client in two ways:
- Token validation:
- For each incoming request that would mutate state:
- We extract the token from the request headers.
- We split the token into the signature and the message.
- We recalculate the signature using the secret key and compare them.
- If the signature is valid and the token matches the value stored in the cookie, the request is allowed to proceed.
- For each incoming request that would mutate state:
Cookies
By default, the cookies are set to HTTPOnly, SameSite: Strict, and Secure.
📦 Install
[]
= "0.3.0"
🗝️ Usage
With axum
use SocketAddr;
use ;
use StatusCode;
use ;
async
async
async
[!NOTE] See the examples for a full example.
🥰 Thank you
- I read a lot of the tower-sessions codebase to figure out how to make a tower project.
- The tokio community answered a lot of silly questions.