Struct poem::middleware::Csrf
source · 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
sourceimpl 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
sourceimpl<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 RefUnwindSafe for Csrf
impl Send for Csrf
impl Sync for Csrf
impl Unpin for Csrf
impl UnwindSafe for Csrf
Blanket Implementations
sourceimpl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more