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, the attacker exploits the user's logged-in status to send malicious requests on their behalf.
How CSRF Attacks Work
The attack typically follows these steps:
- 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 action by the user.
Protection Strategies
Salvo provides CSRF middleware to safeguard your application against such attacks:
- Adding a hidden CSRF token to forms
- Verifying that user-submitted requests contain a valid CSRF token
- By default, validating POST, PATCH, DELETE, and PUT requests
CSRF Implementation in Salvo
Csrf
is a struct that implements the Handler
trait and includes a 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:
- CookieStore: Stores the token in a cookie and verifies whether the
csrf-token
in the request header or form matches the cookie value.
- SessionStore: Stores the token in the session and requires the session middleware to be used together.
Example Code (cookie store)
import { Tab, Tabs } from 'rspress/theme';
import CsrfCookieStoreCode from '../../../../codes_md/csrf-cookie-store/src/main.mdx';
import CsrfCookieStoreCargoCode from '../../../../codes_md/csrf-cookie-store/Cargo.mdx';
import CsrfSessionStoreCode from '../../../../codes_md/csrf-session-store/src/main.mdx';
import CsrfSessionStoreCargoCode from '../../../../codes_md/csrf-session-store/Cargo.mdx';
<Tabs>
<Tab label="main.rs">
<CsrfCookieStoreCode/>
</Tab>
<Tab label="Cargo.toml">
<CsrfCookieStoreCargoCode/>
</Tab>
</Tabs>
Example Code (session store)
<Tabs>
<Tab label="main.rs">
<CsrfSessionStoreCode/>
</Tab>
<Tab label="Cargo.toml">
<CsrfSessionStoreCargoCode/>
</Tab>
</Tabs>