CSRF (Cross-Site Request Forgery) protection for Rocket web framework https://crates.io/crates/rocket_csrf
Go to file
Alex Kotov e464e61f13
Bump version (0.0.1)
2020-10-17 03:26:21 +05:00
src Add existing code 2020-10-17 02:41:07 +05:00
.gitignore Add existing code 2020-10-17 02:41:07 +05:00
Cargo.toml Bump version (0.0.1) 2020-10-17 03:26:21 +05:00
LICENSE Add LICENSE 2020-10-17 02:47:32 +05:00
README.md Fix README.md 2020-10-17 03:24:15 +05:00

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
}