Crates.io | rocket_csrf |
lib.rs | rocket_csrf |
version | |
source | src |
created_at | 2020-10-16 21:59:58.113451 |
updated_at | 2021-03-06 03:18:59.880388 |
description | CSRF (Cross-Site Request Forgery) protection for Rocket web framework |
homepage | https://github.com/kotovalexarian/rocket_csrf |
repository | https://github.com/kotovalexarian/rocket_csrf.git |
max_upload_size | |
id | 300980 |
Cargo.toml error: | TOML parse error at line 21, column 10 | 21 | readme = true | ^^^^ invalid type: boolean `true`, expected a string |
size | 0 |
CSRF (Cross-Site Request Forgery) protection for Rocket web framework.
WARNING! The implementation is very simple for now and may not be ready for production.
Discussion about CSRF protection in Rocket is here.
Attach fairing to the Rocket instance:
#![feature(decl_macro)]
#[macro_use] extern crate rocket;
#[macro_use] extern crate serde_derive;
use rocket_contrib::templates::Template;
fn main() {
rocket::ignite()
.attach(rocket_csrf::Fairing::default())
.attach(Template::fairing())
.mount("/", routes![new, 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):
use rocket::response::Redirect;
use rocket::request::Form;
use rocket_contrib::templates::Template;
use rocket_csrf::CsrfToken;
#[get("/comments/new")]
fn new(csrf_token: CsrfToken) -> Template {
// your code
}
#[post("/comments", data = "<form>")]
fn create(csrf_token: CsrfToken, form: Form<Comment>) -> Redirect {
// your code
}
Get CSRF token from guard to use it in templates:
#[get("/comments/new")]
fn new(csrf_token: CsrfToken) -> Template {
let authenticity_token: &str = csrf_token.authenticity_token();
// your code
}
Add CSRF token to your HTML forms in templates:
<form method="post" action="/comments">
<input type="hidden" name="authenticity_token" value="{{ authenticity_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_token: CsrfToken, form: Form<Comment>) -> Redirect {
if let Err(_) = csrf_token.verify(&form.authenticity_token) {
return Redirect::to(uri!(new));
}
// your code
}
See the complete code in minimal example.
X-CSRF-Token
header.X-CSRF-Token
header.