Skip to main content

Module jwt

Module jwt 

Source
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::extensions by JwtAuth
JwtAuth
Middleware requiring Authorization: Bearer <jwt>
Validation
What decode_with checks besides signature, exp and nbf

Functions§

decode
Verify signature, exp and nbf and return the claims
decode_with
Like decode with leeway, issuer and audience checks
encode
Sign claims as an HS256 token
expires_in
exp value for a token that lives secs seconds from now
now
Seconds since the Unix epoch