pub struct Csrf { /* private fields */ }
Available on crate feature csrf only.
Expand description

Middleware for Cross-Site Request Forgery (CSRF) protection.

Example

use poem::{
    get, handler,
    http::{header, Method, StatusCode},
    middleware::Csrf,
    post,
    test::TestClient,
    web::{cookie::Cookie, CsrfToken, CsrfVerifier},
    Endpoint, EndpointExt, Error, Request, Result, Route,
};
use serde::Deserialize;

#[handler]
async fn login_ui(token: &CsrfToken) -> String {
    token.0.clone()
}

#[handler]
async fn login(verifier: &CsrfVerifier, req: &Request) -> Result<String> {
    let csrf_token = req
        .header("X-CSRF-Token")
        .ok_or_else(|| Error::from_status(StatusCode::UNAUTHORIZED))?;

    if !verifier.is_valid(&csrf_token) {
        return Err(Error::from_status(StatusCode::UNAUTHORIZED));
    }

    Ok(format!("login success"))
}

let app = Route::new()
    .at("/", get(login_ui).post(login))
    .with(Csrf::new());
let cli = TestClient::new(app);

let resp = cli.get("/").send().await;
resp.assert_status_is_ok();

let cookie = resp.0.headers().get(header::SET_COOKIE).unwrap();
let cookie = Cookie::parse(cookie.to_str().unwrap()).unwrap();
let csrf_token = resp.0.into_body().into_string().await.unwrap();

let resp = cli
    .post("/")
    .header("X-CSRF-Token", csrf_token)
    .header(
        header::COOKIE,
        format!("{}={}", cookie.name(), cookie.value_str()),
    )
    .send()
    .await;
resp.assert_status_is_ok();
resp.assert_text("login success").await;

Implementations

Create Csrf middleware.

Sets AES256 key to provide signed, encrypted CSRF tokens and cookies.

Sets the Secure to the csrf cookie. Default is true.

Sets the HttpOnly to the csrf cookie. Default is true.

Sets the SameSite to the csrf cookie. Default is SameSite::Strict.

Sets the protection ttl. This will be used for both the cookie expiry and the time window over which CSRF tokens are considered valid.

The default for this value is one day.

Trait Implementations

Returns the “default value” for a type. Read more
New endpoint type. Read more
Transform the input Endpoint to another one.

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Attaches the current Context to this type, returning a WithContext wrapper. Read more
Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Should always be Self
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more