rocket_csrf
CSRF (Cross-Site Request Forgery) protection for Rocket web framework.
Usage
Attach fairing to the Rocket
instance:
fn main() {
rocket::ignite()
.attach(rocket_csrf::Fairing::new())
.mount("/", routes![index, create])
.launch();
}
Add guard to any
request where you want to have access to session's CSRF token (e.g. to include
it in forms) or verify it (e.g. to validate form):
#[get("/comments/new")]
fn index(csrf: rocket_csrf::Guard) -> Template {
}
#[post("/comments", data = "<form>")]
fn create(csrf: rocket_csrf::Guard, form: Form<Comment>) -> Redirect {
}
Get CSRF token from
guard
to use it in templates:
#[get("/comments/new")]
fn index(csrf: rocket_csrf::Guard) -> Template {
let csrf_token: String = csrf.0;
}
Add CSRF token to your HTML forms in
templates:
<form method="post" action="/comments">
<input type="hidden" name="authenticity_token" value="{{ csrf_token }}"/>
</form>
Add attribute authenticity_token to your
forms:
#[derive(FromForm)]
struct Comment {
authenticity_token: String,
}
Validate forms to have valid
authenticity token:
#[post("/comments", data = "<form>")]
fn create(csrf: rocket_csrf::Guard, form: Form<Comment>) -> Redirect {
if Err(_) = csrf.verify(form.authenticity_token) {
return Redirect::to(uri!(index));
}
}