CSRF (Cross-Site Request Forgery) protection for Rocket web framework
https://crates.io/crates/rocket_csrf
Alex Kotov e464e61f13 | ||
---|---|---|
src | ||
.gitignore | ||
Cargo.toml | ||
LICENSE | ||
README.md |
README.md
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 {
// your code
}
#[post("/comments", data = "<form>")]
fn create(csrf: rocket_csrf::Guard, form: Form<Comment>) -> Redirect {
// your code
}
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;
// your code
}
Add CSRF token to your HTML forms in templates:
<form method="post" action="/comments">
<input type="hidden" name="authenticity_token" value="{{ csrf_token }}"/>
<!-- your fields -->
</form>
Add attribute authenticity_token
to your
forms:
#[derive(FromForm)]
struct Comment {
authenticity_token: String,
// your attributes
}
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));
}
// your code
}