16 releases

0.4.2 Jan 20, 2025
0.4.1 Aug 29, 2021
0.4.0 Jun 16, 2020
0.3.1 Oct 27, 2019
0.0.1 Feb 25, 2017

#1204 in Web programming

Download history 200/week @ 2024-10-29 490/week @ 2024-11-05 299/week @ 2024-11-12 314/week @ 2024-11-19 356/week @ 2024-11-26 306/week @ 2024-12-03 373/week @ 2024-12-10 239/week @ 2024-12-17 143/week @ 2024-12-24 132/week @ 2024-12-31 263/week @ 2025-01-07 361/week @ 2025-01-14 428/week @ 2025-01-21 404/week @ 2025-01-28 505/week @ 2025-02-04 411/week @ 2025-02-11

1,879 downloads per month
Used in 7 crates (3 directly)

MIT license

37KB
710 lines

rust-csrf

Primitives for building CSRF protection.

Documentation is hosted at docs.rs. This crate is used by iron-csrf and be used as a reference for using rust-csrf in other applications.

Contributing

Please make all pull requests to the develop branch.

License

This work is licensed under the MIT license. See LICENSE for details.


lib.rs:

Crate providing cross-site request forgery (CSRF) protection primitives

Overview

csrf provides the basic building blocks you will need to implement CSRF protection for the web framework of your choice. csrf generates encrypyed, signed tokens and cookies, and verifies that they have not been tampered with and that they match.

This crate is used by iron-csrf and be used as a reference for using csrf in other applications.

Hello, CSRF.

A simple example of how to use this library is as follows.

extern crate csrf;
extern crate data_encoding;

use csrf::{AesGcmCsrfProtection, CsrfProtection};
use data_encoding::BASE64;

fn main() {
    let protect = AesGcmCsrfProtection::from_key(*b"01234567012345670123456701234567");

    let (token, cookie) = protect.generate_token_pair(None, 300)
        .expect("couldn't generate token/cookie pair");

    let token_str = token.b64_string();
    let cookie_str = cookie.b64_string();

    // add them to outgoing response

    // wait for incoming connection

    // extract them from an incoming request

    let token_bytes = BASE64.decode(token_str.as_bytes()).expect("token not base64");
    let cookie_bytes = BASE64.decode(cookie_str.as_bytes()).expect("cookie not base64");

    let parsed_token = protect.parse_token(&token_bytes).expect("token not parsed");
    let parsed_cookie = protect.parse_cookie(&cookie_bytes).expect("cookie not parsed");

    assert!(protect.verify_token_pair(&parsed_token, &parsed_cookie).is_ok());
}

Warning

CSRF protection is not a substitute for authentication or authorization. It only exists to prevent malicious entities from forcing users to take actions they did not intend. If this is unclear, please read the Wikipedia article.

Dependencies

~3.5MB
~59K SLoC