Expand description
HS256 JSON Web Tokens and a bearer-token middleware (feature jwt)
Only HS256 is accepted: tokens with any other alg (including none)
are rejected, signatures are compared in constant time, and exp / nbf
are checked. Secrets must be at least 32 bytes (RFC 7518, section 3.2).
use ullun::jwt;
let secret = b"0123456789abcdef0123456789abcdef";
let token = jwt::encode(&serde_json::json!({ "sub": "ann", "exp": jwt::expires_in(3600) }), secret).unwrap();
let claims: serde_json::Value = jwt::decode(&token, secret).unwrap();
assert_eq!(claims["sub"], "ann");As middleware, valid claims are stored in req.extensions:
use ullun::prelude::*;
use ullun::jwt::{Claims, JwtAuth};
App::new()
.group("/api", |g| {
g.middleware(JwtAuth::new("0123456789abcdef0123456789abcdef"))
.get("/me", |req: Request| async move {
let claims = req.extensions.get::<Claims>().expect("set by JwtAuth");
Ok(Response::json(&claims.0))
})
})
.run("127.0.0.1:3000")
.await
.unwrap();Structs§
- Claims
- Verified claims, inserted into
Request::extensionsbyJwtAuth - JwtAuth
- Middleware requiring
Authorization: Bearer <jwt> - Validation
- What
decode_withchecks besides signature,expandnbf
Functions§
- decode
- Verify signature,
expandnbfand return the claims - decode_
with - Like
decodewith leeway, issuer and audience checks - encode
- Sign
claimsas an HS256 token - expires_
in expvalue for a token that livessecsseconds from now- now
- Seconds since the Unix epoch