CSRF Protection
Cross-Site Request Forgery (CSRF) is an attack in which a malicious site causes a user’s browser to send an unwanted request to another application where the user is authenticated.
Mach provides CSRF protection using the double-submit cookie pattern.
Enabling CSRF Protection
Section titled “Enabling CSRF Protection”Enable CSRF protection when configuring the application:
int main() { mach::AppBuilder builder;
builder.addCsrf();}Once enabled, Mach manages CSRF tokens and validates protected requests automatically.
How CSRF Protection Works
Section titled “How CSRF Protection Works”Mach uses a CSRF token that is submitted in two places: a cookie and a request header.
The flow is:
- Mach generates a CSRF token and sends it to the client in a cookie.
- The client reads the token from the cookie.
- For protected requests, the client sends the same token in the CSRF request header.
- Mach compares the token in the header with the token in the cookie.
- If the tokens match, the request continues. Otherwise, the request is rejected with a 403 Forbidden response.
Because another site cannot read the CSRF cookie and reproduce its value in the request header, this prevents forged cross-site requests from passing CSRF validation.
Sending the CSRF Token
Section titled “Sending the CSRF Token”When making a protected request from a browser, read the CSRF token from the cookie and include it in the CSRF header.
For example:
const token = document.cookie .split("; ") .find((cookie) => cookie.startsWith("csrf-token=")) ?.split("=")[1];
await fetch("/api/profile", { method: "POST", headers: { "Content-Type": "application/json", "X-Mach-CSRF": token, }, credentials: "include", body: JSON.stringify({ displayName: "Alex", }),});The cookie and header names must match those configured by the application.
Customizing Token Names
Section titled “Customizing Token Names”You can customize the cookie and request header used for the CSRF token:
builder.addCsrf([](mach::CsrfBuilder& csrf) { csrf.cookieName("csrf-token") .headerName("X-Mach-CSRF");});The client must use the configured names when submitting the token.
For details about configuring the CSRF cookie and header names, see CsrfBuilder.
Next Steps
Section titled “Next Steps”For details about configuring the CSRF cookie and header names, see CsrfBuilder.