[−][src]Module roa::jwt
This is supported on
feature="jwt"
only.This module provides middleware JwtGuard
and a context extension JwtVerifier
.
Example
use roa::jwt::{guard, DecodingKey}; use roa::{App, Context}; use roa::http::header::AUTHORIZATION; use roa::http::StatusCode; use roa::preload::*; use async_std::task::spawn; use jsonwebtoken::{encode, Header, EncodingKey}; use serde::{Deserialize, Serialize}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; #[derive(Debug, Serialize, Deserialize)] struct User { sub: String, company: String, exp: u64, id: u64, name: String, } const SECRET: &[u8] = b"123456"; async fn test(ctx: &mut Context) -> roa::Result { let user: User = ctx.claims()?; assert_eq!(0, user.id); assert_eq!("Hexilee", &user.name); Ok(()) } #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let (addr, server) = App::new() .gate(guard(DecodingKey::from_secret(SECRET))) .end(test).run()?; spawn(server); let mut user = User { sub: "user".to_string(), company: "None".to_string(), exp: (SystemTime::now() + Duration::from_secs(86400)) .duration_since(UNIX_EPOCH)? .as_secs(), id: 0, name: "Hexilee".to_string(), }; let client = reqwest::Client::new(); let resp = client .get(&format!("http://{}", addr)) .header( AUTHORIZATION, format!( "Bearer {}", encode( &Header::default(), &user, &EncodingKey::from_secret(SECRET) )? ), ) .send() .await?; assert_eq!(StatusCode::OK, resp.status()); Ok(()) }
Structs
DecodingKey | feature="jwt" All the different kind of keys we can use to decode a JWT This key can be re-used so make sure you only initialize it once if you can for better performance |
JwtGuard | feature="jwt" A middleware to deny unauthorized requests. |
Validation | feature="jwt" Contains the various validations that are applied after decoding a JWT. |
Traits
JwtVerifier | feature="jwt" A context extension.
This extension must be used in downstream of middleware |
Functions
guard | feature="jwt" Guard by default validation. |