Struct poem::middleware::Csrf

source ·
pub struct Csrf { /* private fields */ }
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§

source§

impl Csrf

source

pub fn new() -> Self

Create Csrf middleware.

source

pub fn key(self, key: [u8; 32]) -> Self

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

source

pub fn secure(self, value: bool) -> Self

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

source

pub fn http_only(self, value: bool) -> Self

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

source

pub fn same_site(self, value: impl Into<Option<SameSite>>) -> Self

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

source

pub fn ttl(self, ttl: Duration) -> Self

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§

source§

impl Default for Csrf

source§

fn default() -> Self

Returns the “default value” for a type. Read more
source§

impl<E: Endpoint> Middleware<E> for Csrf

§

type Output = CookieJarManagerEndpoint<CsrfEndpoint<E>>

New endpoint type. Read more
source§

fn transform(&self, ep: E) -> Self::Output

Transform the input Endpoint to another one.

Auto Trait Implementations§

§

impl Freeze for Csrf

§

impl RefUnwindSafe for Csrf

§

impl Send for Csrf

§

impl Sync for Csrf

§

impl Unpin for Csrf

§

impl UnwindSafe for Csrf

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

source§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

source§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

source§

fn implicit( self, class: Class, constructed: bool, tag: u32 ) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> FutureExt for T

source§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
source§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext wrapper. Read more
source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

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

source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> TowerCompatExt for T

source§

fn compat<ResBody, Err, Fut>(self) -> TowerCompatEndpoint<Self>
where ResBody: Body + Send + Sync + 'static, ResBody::Data: Into<Bytes> + Send + 'static, ResBody::Error: StdError + Send + Sync + 'static, Err: Into<Error>, Self: Service<Request<BoxBody<Bytes, Error>>, Response = Response<ResBody>, Error = Err, Future = Fut> + Clone + Send + Sync + Sized + 'static, Fut: Future<Output = Result<Response<ResBody>, Err>> + Send + 'static,

Available on crate feature tower-compat only.
Converts a tower service to a poem endpoint.
source§

impl<L> TowerLayerCompatExt for L

source§

fn compat(self) -> TowerCompatMiddleware<Self>
where Self: Sized,

Available on crate feature tower-compat only.
Converts a tower layer to a poem middleware.
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

source§

fn vzip(self) -> V

source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more