pub struct Decoder(/* private fields */);Expand description
A decoder for JSON Web Tokens (JWTs).
To extract a JWT value from a request header, this decoder must be provided
to the router using the with_state method.
§Examples
You can pass the decoder directly:
use {
axum::{Router, routing},
axum_jwt::{Claims, Decoder, jsonwebtoken::DecodingKey},
serde::Deserialize,
};
#[derive(Deserialize)]
struct User {
sub: String,
}
async fn hello(Claims(u): Claims<User>) -> String {
format!("Hello, {}!", u.sub)
}
let decoder = Decoder::from_key(DecodingKey::from_secret(b"secret"));
let app = Router::new()
.route("/", routing::get(hello))
.with_state(decoder);If the application needs to store additional state, you can define a custom
type that contains the decoder. You’ll also need the application state to
be cheap to clone, so it makes sense to wrap it in an Arc. In this
case, you can provide the decoder by implementing the AsRef trait for
your custom state.
struct App {
decoder: Decoder,
users_online: Mutex<Vec<User>>,
}
impl AsRef<Decoder> for App {
fn as_ref(&self) -> &Decoder {
&self.decoder
}
}
let decoder = Decoder::from_key(DecodingKey::from_secret(b"secret"));
let app = Router::new()
.route("/", routing::get(hello))
.with_state(Arc::new(App {
decoder,
users_online: Mutex::default(),
}));Implementations§
Source§impl Decoder
impl Decoder
Sourcepub fn from_key(key: DecodingKey) -> Self
pub fn from_key(key: DecodingKey) -> Self
Creates a decoder from the provided decoding key.
Sourcepub fn new(key: DecodingKey, validation: Validation) -> Self
pub fn new(key: DecodingKey, validation: Validation) -> Self
Creates a decoder from the provided decoding key and validation.
Sourcepub fn with_keys(keys: Vec<DecodingKey>, validation: Validation) -> Option<Self>
pub fn with_keys(keys: Vec<DecodingKey>, validation: Validation) -> Option<Self>
Creates a decoder from the provided decoding keys and validation.
If the given vector is empty, this constructor will return None.
Sourcepub fn keys(&self) -> &[DecodingKey]
pub fn keys(&self) -> &[DecodingKey]
Returns a slice of decoding keys.
Sourcepub fn validation(&self) -> &Validation
pub fn validation(&self) -> &Validation
Returns a reference to the validation.