9 releases (5 breaking)

0.7.0 Sep 4, 2022
0.6.1 May 25, 2022
0.6.0 Apr 10, 2022
0.5.0 Feb 27, 2022
0.2.2 Aug 19, 2021

#471 in HTTP server

Download history 76/week @ 2023-10-28 82/week @ 2023-11-04 52/week @ 2023-11-11 25/week @ 2023-11-18 74/week @ 2023-11-25 28/week @ 2023-12-02 8/week @ 2023-12-09 26/week @ 2023-12-16 43/week @ 2023-12-23 16/week @ 2023-12-30 23/week @ 2024-01-06 27/week @ 2024-01-13 31/week @ 2024-01-20 66/week @ 2024-01-27 13/week @ 2024-02-03 73/week @ 2024-02-10

194 downloads per month


770 lines


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.


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.

async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        let csrf = Csrf::<StdRng>::new()
            .set_cookie(Method::GET, "/login");
    .bind(("", 8080))?

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

struct LoginForm {
    csrf_token: CsrfToken,
    username: String,
    password: String,

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

/// Validates a login form that has a CSRF token.
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.


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.


Licensed under either of

at your option.


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.


~535K SLoC