[][src]Module actix_web::middleware::csrf

A filter for cross-site request forgery (CSRF).

This middleware is stateless and based on request headers.

By default requests are allowed only if one of these is true:

  • The request method is safe (GET, HEAD, OPTIONS). It is the applications responsibility to ensure these methods cannot be used to execute unwanted actions. Note that upgrade requests for websockets are also considered safe.
  • The Origin header (added automatically by the browser) matches one of the allowed origins.
  • There is no Origin header but the Referer header matches one of the allowed origins.

Use CsrfFilter::allow_xhr() if you want to allow requests with unprotected methods via CORS.

Example

use actix_web::middleware::csrf;
use actix_web::{http, App, HttpRequest, HttpResponse};

fn handle_post(_: &HttpRequest) -> &'static str {
    "This action should only be triggered with requests from the same site"
}

fn main() {
    let app = App::new()
        .middleware(
            csrf::CsrfFilter::new().allowed_origin("https://www.example.com"),
        )
        .resource("/", |r| {
            r.method(http::Method::GET).f(|_| HttpResponse::Ok());
            r.method(http::Method::POST).f(handle_post);
        })
        .finish();
}

In this example the entire application is protected from CSRF.

Structs

CsrfFilter

A middleware that filters cross-site requests.

Enums

CsrfError

Potential cross-site request forgery detected.