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
impl Csrf
sourcepub fn key(self, key: [u8; 32]) -> Self
pub fn key(self, key: [u8; 32]) -> Self
Sets AES256 key to provide signed, encrypted CSRF tokens and cookies.
sourcepub fn http_only(self, value: bool) -> Self
pub fn http_only(self, value: bool) -> Self
Sets the HttpOnly
to the csrf cookie. Default is true
.
Trait Implementations§
source§impl<E: Endpoint> Middleware<E> for Csrf
impl<E: Endpoint> Middleware<E> for Csrf
§type Output = CookieJarManagerEndpoint<CsrfEndpoint<E>>
type Output = CookieJarManagerEndpoint<CsrfEndpoint<E>>
New endpoint type. Read more
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<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
source§impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
source§impl<T> FutureExt for T
impl<T> FutureExt for T
source§fn with_context(self, otel_cx: Context) -> WithContext<Self>
fn with_context(self, otel_cx: Context) -> WithContext<Self>
source§fn with_current_context(self) -> WithContext<Self>
fn with_current_context(self) -> WithContext<Self>
source§impl<T> Instrument for T
impl<T> Instrument for T
source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
source§impl<T> TowerCompatExt for T
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,
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.