10 releases (6 breaking)

0.8.0 Nov 8, 2024
0.7.0 Sep 4, 2022
0.6.1 May 25, 2022
0.6.0 Apr 10, 2022
0.2.2 Aug 19, 2021

#135 in HTTP server

Download history 5266/week @ 2024-07-29 5386/week @ 2024-08-05 4098/week @ 2024-08-12 4457/week @ 2024-08-19 3201/week @ 2024-08-26 3309/week @ 2024-09-02 4536/week @ 2024-09-09 4164/week @ 2024-09-16 4363/week @ 2024-09-23 4447/week @ 2024-09-30 4902/week @ 2024-10-07 4659/week @ 2024-10-14 3693/week @ 2024-10-21 3221/week @ 2024-10-28 2906/week @ 2024-11-04 3370/week @ 2024-11-11

13,461 downloads per month

MIT/Apache

45KB
771 lines

actix-csrf

CSRF middleware for actix-web 4.0.0 or newer that uses the Double-Submit Token pattern.

This crate has not yet been audited. Use in production at your own risk.

Usage

Installing the middleware is standard: Specify a cryptographically secure RNG to use, and declare which paths should set a CSRF cookie and when should validate a CSRF cookie.

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        let csrf = Csrf::<StdRng>::new()
            .set_cookie(Method::GET, "/login");
        App::new().wrap(csrf).service(login_ui).service(login)
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}

Then, use the CsrfCookie extractor to pull the CSRF cookie and validate it with a CSRF token provided as part of the protected request.

#[derive(Deserialize)]
struct LoginForm {
    csrf_token: CsrfToken,
    username: String,
    password: String,
}

impl CsrfGuarded for LoginForm {
    fn csrf_token(&self) -> &CsrfToken {
        &self.csrf_token
    }
}

/// Validates a login form that has a CSRF token.
#[post("/login")]
async fn login(form: Csrf<Form<LoginForm>>) -> impl Responder {
    // At this point, we have a valid CSRF token, so we can treat the request
    // as legitimate.

    HttpResponse::Ok().finish()
}

This is only one of many ways to use the Double-Submit Token pattern; see the docs and examples for more information.

Security Considerations

There are advantages and limitations to using the Double Submit Token pattern. Users are highly recommended to read the Owasp article on CSRF Protection before using this middleware.

This crate attempts to have secure defaults, and users must explicitly disable defense-in-depth features.

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Dependencies

~15–26MB
~435K SLoC