Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 38 ยท Authentication and Errors

JWT Authentication in Axum

Issue and verify JSON Web Tokens in Axum with the jsonwebtoken crate: claims, expiry, secrets, Bearer headers, refresh tokens and when sessions are better, with a runnable signed-token stand-in.

After a user logs in, the server needs a way to recognise them on later requests. There are two classic designs. With server-side sessions, the server stores state and gives the browser an opaque id in a cookie. With tokens, the server signs a small piece of data (who you are, when it expires) and gives it to the client, which sends it back on every request; the server only needs to verify the signature, with no lookup. The most common token format is the JSON Web Token (JWT).

This lesson shows how to issue and verify JWTs in Axum with the jsonwebtoken crate, what belongs in a token, and what to watch out for. The crate is not available on this site's runner, so the real code is read-only; the runnable stand-in builds a toy signed token so you can see the mechanics. The stand-in's signature is not secure; real tokens use HMAC-SHA256 or an asymmetric algorithm.

Anatomy of a JWT

A JWT is three base64url parts separated by dots: header.payload.signature.

TEXT
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
.eyJzdWIiOiI0MiIsInJvbGUiOiJhZG1pbiIsImV4cCI6MTc2NzIyNTYwMH0
.k3...signature...
  • The header names the algorithm (HS256, RS256, EdDSA).
  • The payload holds claims: sub (subject, the user id), exp (expiry, Unix seconds), iat (issued at), plus your own such as role.
  • The signature covers header and payload using a secret (HS256) or private key.

The payload is only encoded, not encrypted. Anyone holding a token can read it, so never put secrets or sensitive personal data in claims. The signature guarantees nobody can change it without the key.

Issuing tokens

Rust
// Real code: read-only. Cargo: jsonwebtoken = "9"
use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation};
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
pub struct Claims {
    pub sub: i64,      // user id
    pub role: String,
    pub exp: usize,    // required by Validation::default()
    pub iat: usize,
}

pub fn issue_token(user_id: i64, role: &str, secret: &[u8]) -> Result<String, AppError> {
    let now = chrono::Utc::now().timestamp() as usize;
    let claims = Claims { sub: user_id, role: role.into(), iat: now, exp: now + 15 * 60 };
    encode(&Header::default(), &claims, &EncodingKey::from_secret(secret))
        .map_err(|e| AppError::Internal(e.into()))
}

pub fn verify_token(token: &str, secret: &[u8]) -> Result<Claims, AppError> {
    decode::<Claims>(token, &DecodingKey::from_secret(secret), &Validation::default())
        .map(|data| data.claims)
        .map_err(|_| AppError::Unauthorized)
}

Validation::default() checks the signature and the exp claim, and pins the algorithm to HS256, which matters: never accept whatever algorithm the token claims. The secret must be long and random (32 bytes or more), loaded from configuration and never committed to git.

The login response and the Bearer header

Login returns the token in JSON; clients send it back in the Authorization header:

TEXT
Authorization: Bearer eyJhbGciOi...

Reading it in a handler is the job of an extractor, covered in authentication middleware and authorization. A small taste of the parsing step:

Rust
fn bearer_token(header: Option<&str>) -> Option<&str> {
    header?.strip_prefix("Bearer ")
}

Stand-in: a toy signed token

The stand-in implements the same pipeline with our own small base64url encoder and a keyed toy mixing function in place of HMAC. It demonstrates what verification catches: tampering, a wrong key and expiry.

Rust Issue and verify a signed token (TOY stand-in, not secure)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The forged token fails because the signature was computed over the original payload. That is the entire security promise of a signed token: integrity, not secrecy.

Short-lived access plus refresh tokens

A JWT cannot be revoked before it expires (the server holds no list), so keep access tokens short, 5 to 15 minutes. To avoid forcing a login every quarter hour, issue a long-lived refresh token that is stored (hashed) in the database and exchanged for new access tokens. Because it is stored, you can delete it to log a user out everywhere. Rotate refresh tokens on each use and detect reuse.

Rust Access plus refresh flow (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

JWT or sessions?

JWT access token Server session
State none on server (stateless verify) stored in DB/Redis
Revocation hard; wait for expiry instant
Browser apps store carefully (see below) cookie, simple
APIs and mobile natural fit works, needs cookie jar

For a classic browser app, an HttpOnly, Secure, SameSite cookie holding a session id (the tower-sessions crate) is often simpler and safer than JWTs in localStorage, which any injected script can read. Choose JWTs when you have mobile or third-party API clients or many independent services that must verify identity without sharing a database.

Common mistakes

  • Weak or committed secrets; use 32+ random bytes from the environment.
  • Not checking exp, or accepting alg: none (the library rejects it with Validation pinned to your algorithm).
  • Putting secrets or large payloads in claims.
  • Long-lived access tokens with no revocation plan.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the signature of a JWT protect?

    The payload is only base64-encoded. The signature proves it was not modified since the server issued it.
  2. 2. Which claim makes a token stop working after a time?

    exp is the expiry time in Unix seconds, and Validation checks it for you.
  3. 3. Why are access tokens kept short-lived?

    Stateless tokens stay valid until expiry. Short lifetimes limit the damage of theft.
  4. 4. Where must the signing secret come from?

    Secrets in source control leak. Load them from the environment at startup.

Summary

  • A JWT is header.payload.signature; the payload is readable, the signature proves integrity.
  • Issue with encode, verify with decode and Validation; include sub and exp.
  • Keep access tokens short and use stored, rotated refresh tokens for longevity.
  • Secrets come from configuration and are long and random.
  • Sessions in cookies are often a better fit for browser-only apps.

Next: Authentication Middleware and Authorization