Struct axum_extra::extract::SignedCookieJar
source · pub struct SignedCookieJar<K = Key> { /* private fields */ }
cookie-signed
and cookie
only.Expand description
Extractor that grabs signed cookies from the request and manages the jar.
All cookies will be signed and verified with a Key
. Do not use this to store private data
as the values are still transmitted in plaintext.
Note that methods like SignedCookieJar::add
, SignedCookieJar::remove
, etc updates the
SignedCookieJar
and returns it. This value must be returned from the handler as part of
the response for the changes to be propagated.
Example
use axum::{
Router,
routing::{post, get},
extract::{TypedHeader, FromRef},
response::{IntoResponse, Redirect},
headers::authorization::{Authorization, Bearer},
http::StatusCode,
};
use axum_extra::extract::cookie::{SignedCookieJar, Cookie, Key};
async fn create_session(
TypedHeader(auth): TypedHeader<Authorization<Bearer>>,
jar: SignedCookieJar,
) -> Result<(SignedCookieJar, Redirect), StatusCode> {
if let Some(session_id) = authorize_and_create_session(auth.token()).await {
Ok((
// the updated jar must be returned for the changes
// to be included in the response
jar.add(Cookie::new("session_id", session_id)),
Redirect::to("/me"),
))
} else {
Err(StatusCode::UNAUTHORIZED)
}
}
async fn me(jar: SignedCookieJar) -> Result<(), StatusCode> {
if let Some(session_id) = jar.get("session_id") {
// fetch and render user...
} else {
Err(StatusCode::UNAUTHORIZED)
}
}
async fn authorize_and_create_session(token: &str) -> Option<String> {
// authorize the user and create a session...
}
// our application state
#[derive(Clone)]
struct AppState {
// that holds the key used to sign cookies
key: Key,
}
// this impl tells `SignedCookieJar` how to access the key from our state
impl FromRef<AppState> for Key {
fn from_ref(state: &AppState) -> Self {
state.key.clone()
}
}
let state = AppState {
// Generate a secure key
//
// You probably don't wanna generate a new one each time the app starts though
key: Key::generate(),
};
let app = Router::new()
.route("/sessions", post(create_session))
.route("/me", get(me))
.with_state(state);
Implementations
sourceimpl SignedCookieJar
impl SignedCookieJar
sourcepub fn from_headers(headers: &HeaderMap, key: Key) -> Self
pub fn from_headers(headers: &HeaderMap, key: Key) -> Self
Create a new SignedCookieJar
from a map of request headers.
The valid cookies in headers
will be added to the jar.
This is inteded to be used in middleware and other places where it might be difficult to
run extractors. Normally you should create SignedCookieJar
s through FromRequestParts
.
sourcepub fn new(key: Key) -> Self
pub fn new(key: Key) -> Self
Create a new empty SignedCookieJar
.
This is inteded to be used in middleware and other places where it might be difficult to
run extractors. Normally you should create SignedCookieJar
s through FromRequestParts
.
sourceimpl<K> SignedCookieJar<K>
impl<K> SignedCookieJar<K>
sourcepub fn get(&self, name: &str) -> Option<Cookie<'static>>
pub fn get(&self, name: &str) -> Option<Cookie<'static>>
Get a cookie from the jar.
If the cookie exists and its authenticity and integrity can be verified then it is returned in plaintext.
Example
use axum_extra::extract::cookie::SignedCookieJar;
use axum::response::IntoResponse;
async fn handle(jar: SignedCookieJar) {
let value: Option<String> = jar
.get("foo")
.map(|cookie| cookie.value().to_owned());
}
sourcepub fn remove(self, cookie: Cookie<'static>) -> Self
pub fn remove(self, cookie: Cookie<'static>) -> Self
Remove a cookie from the jar.
Example
use axum_extra::extract::cookie::{SignedCookieJar, Cookie};
use axum::response::IntoResponse;
async fn handle(jar: SignedCookieJar) -> SignedCookieJar {
jar.remove(Cookie::named("foo"))
}
sourcepub fn add(self, cookie: Cookie<'static>) -> Self
pub fn add(self, cookie: Cookie<'static>) -> Self
Add a cookie to the jar.
The value will automatically be percent-encoded.
Example
use axum_extra::extract::cookie::{SignedCookieJar, Cookie};
use axum::response::IntoResponse;
async fn handle(jar: SignedCookieJar) -> SignedCookieJar {
jar.add(Cookie::new("foo", "bar"))
}