CSRF Protection
What is CSRF?
CSRF (Cross-Site Request Forgery) is a web security vulnerability where attackers trick authenticated users into performing unintended actions without their knowledge. In simple terms, attackers exploit a user's logged-in status to send malicious requests on their behalf.
How CSRF Attacks Work
The typical attack process involves:
- The user logs into the target website A and obtains an authentication cookie.
- The user visits a malicious website B.
- Code on malicious website B automatically sends a request to website A, carrying the user's cookie.
- Website A cannot distinguish whether this is a malicious request or a legitimate user action.
Protection Strategies
Salvo provides CSRF middleware to protect your applications from such attacks:
- Add a hidden CSRF token to forms.
- Verify that user-submitted requests contain a valid CSRF token.
- By default, validate POST, PATCH, DELETE, and PUT requests.
Common Token Rotation Strategies
CSRF token systems commonly use one of two rotation strategies:
- Per-session: Reuse the same token until it expires or is removed from the trusted store. This works well with page refreshes, multiple tabs, and browser back or forward navigation.
- Per-request: Issue a fresh token after every accepted request. This shortens the lifetime of each token, but clients must always submit the latest token from the most recent response.
In Salvo, token rotation is configured separately from storage:
- Storage decides where the trusted token lives:
CookieStoreorSessionStore. - Rotation decides how often the token changes:
CsrfRotationPolicy::PerSessionorCsrfRotationPolicy::PerRequest.
Salvo defaults to CsrfRotationPolicy::PerSession. If you want stricter request-level rotation, opt into PerRequest explicitly:
CSRF Implementation in Salvo
Csrf is a struct that implements the Handler trait and includes an internal skipper field to specify requests that should skip validation. By default, it validates Method::POST, Method::PATCH, Method::DELETE, and Method::PUT requests.
Salvo supports two CSRF token storage methods. Storage and rotation are independent choices:
- CookieStore: Stores the token in a cookie and verifies whether the
csrf-tokenin the request headers or form matches the cookie value. - SessionStore: Stores the token in the session and requires the use of session middleware.
Example Code (cookie store)
Example Code (session store)