logo
pub struct Csrf { /* private fields */ }
This is supported 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,
    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 resp = app.call(Request::default()).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let cookie = resp.headers().get(header::SET_COOKIE).unwrap();
let cookie = Cookie::parse(cookie.to_str().unwrap()).unwrap();
let csrf_token = resp.into_body().into_string().await.unwrap();

let resp = app
    .call(
        Request::builder()
            .method(Method::POST)
            .header("X-CSRF-Token", csrf_token)
            .header(
                header::COOKIE,
                format!("{}={}", cookie.name(), cookie.value_str()),
            )
            .finish(),
    )
    .await
    .unwrap();
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(
    resp.into_body().into_string().await.unwrap(),
    "login success"
);

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

Performs the conversion.

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

Performs the conversion.

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