Struct poem::middleware::Csrf [−][src]
pub struct Csrf { /* fields omitted */ }
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
Sets AES256 key to provide signed, encrypted CSRF tokens and cookies.
Sets the HttpOnly
to the csrf cookie. Default is true
.
Sets the SameSite
to the csrf cookie. Default is
SameSite::Strict
.
Trait Implementations
type Output = CookieJarManagerEndpoint<CsrfEndpoint<E>>
type Output = CookieJarManagerEndpoint<CsrfEndpoint<E>>
New endpoint type. Read more
Auto Trait Implementations
impl RefUnwindSafe for Csrf
impl UnwindSafe for Csrf
Blanket Implementations
Mutably borrows from an owned value. Read more
pub fn vzip(self) -> V
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