Crate iron_dsc_csrf [] [src]

Iron middleware providing cross-site request forgery (CSRF) protection.


iron-dsc-csrf is used as an Iron::AroundMiddleware that checks unsafe HTTP methods (for example POST, PUT, and PATCH) for a valid CSRF token.


iron-dsc-csrf uses a method called Double Submit Cookie (or DSC). On the first request to a protected handler, iron-dsc-csrf generates a long random value, called the token. The token is placed into a cookie and provided to the client in the response.

When a client makes an unsafe request, it must provide the token in a way that cannot be triggered without user action and intent. The usual method of providing the token is with a hidden input field in a form.

Upon receiving the unsafe request, iron-dsc-csrf compares the token from the cookie to the token in the submitted data. If the tokens match, the request is allowed, otherwise it is denied.


extern crate iron_dsc_csrf;
extern crate iron;

use iron_dsc_csrf::Csrf;
use iron::AroundMiddleware;
use iron::prelude::*;
use iron::status;

fn main() {
    let csrf = Csrf::new(extract_token);

    let handler = csrf.around(Box::new(index));

    // Make and start the server
    Iron::new(handler); //.http("localhost:8080").unwrap();

fn extract_token(request: &Request) -> Option<String> {
    // Here you can extract the token from the form body, the query string,
    // or anywhere else you like.

    request.url.query().map(|x| x.to_owned())

fn index(request: &mut Request) -> IronResult<Response> {
    let token = request.extensions.get::<Csrf>().unwrap();
    let msg = format!("Hello, CSRF Token: {}", token);
    Ok(Response::with((status::Ok, msg)))



An iron::AroundMiddleware that provides CSRF protection.



The type of Errors used in this middleware.