JWT token claims

Learn what the Claims struct holds, what sub role and exp each mean, and why a token carries identity and expiry and nothing secret

A token is a small signed package, and the claims are the contents of that package. A claim is a named piece of data inside a token, written as a key and a value, and the whole set of claims is the payload, the middle part of the token string. This app puts exactly three claims in every token: who the token belongs to, what role that user has, and when the token stops working. Nothing else goes in, and nothing secret ever goes in.

Where This Fits

The login step mints a token after the password check passes. This page opens that token up and names what is inside it. The claims are the reason the token is useful at all: without them, the token would be a signature over nothing, and the server would learn nothing from checking it. With them, one verified token tells the server the user id, the role, and whether the token is still fresh.

Think of a luggage tag. The tag carries the owner name, the flight number, and the date, and anyone who picks up the bag can read the tag. The tag never carries the combination to the lock, because the tag is visible to everyone who handles the bag. The claims are the tag, and the secret is the combination, which stays off the tag entirely.

The Smallest Working Version

The claims live in one struct, in src/auth.rs, next to the login types. Create a project with the same files as the login page, and add the demo program below it.

Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sqlx = { version = "0.9", features = ["runtime-tokio", "postgres", "macros", "derive"] }
jsonwebtoken = { version = "12", features = ["rust_crypto"] }
argon2 = "0.6"
thiserror = "2.0"

[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
src/auth.rs
use std::time::{SystemTime, UNIX_EPOCH};

use jsonwebtoken::{EncodingKey, Header, encode};
use serde::{Deserialize, Serialize};

use crate::errors::AppError;

#[derive(Debug, Serialize, Deserialize)]
pub struct Claims {
    pub sub: i32,
    pub role: String,
    pub exp: usize,
}

fn expiry_in_one_hour() -> usize {
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .expect("system time is before the Unix epoch")
        .as_secs() as usize;
    now + 3600
}

pub fn create_token(user_id: i32, role: &str, secret: &str) -> Result<String, AppError> {
    let claims = Claims {
        sub: user_id,
        role: role.to_string(),
        exp: expiry_in_one_hour(),
    };
    let key = EncodingKey::from_secret(secret.as_bytes()).map_err(|error| {
        eprintln!("encoding key error: {error}");
        AppError::InternalError
    })?;
    encode(&Header::default(), &claims, &key).map_err(|error| {
        eprintln!("token encode error: {error}");
        AppError::InternalError
    })
}

The struct has three fields, and each field is one claim. sub is an i32, a 32-bit integer, holding the user id. role is a String holding "user" or "admin". exp is a usize, an unsigned integer sized to the machine, holding the expiry time as seconds since the Unix epoch. The derive list matters: Serialize turns the struct into JSON when the token is made, and Deserialize turns JSON back into the struct when the token is checked. Without both, the struct can only travel in one direction.

The demo program below builds a Claims value by hand and prints it as JSON, then mints a real token with the same values and splits it into its three parts. Save it as an example program, which is a small program that Cargo runs with cargo run --example, kept separate from the server itself.

examples/claims_demo.rs
use axum_project::auth::{Claims, create_token};

fn main() {
    let claims = Claims {
        sub: 1,
        role: "user".to_string(),
        exp: 1794648154,
    };
    println!("claims as JSON:");
    println!("{}", serde_json::to_string(&claims).unwrap());
    let token = create_token(1, "user", "test-secret-only-for-local-development").unwrap();
    println!("token:");
    println!("{token}");
    let header = token.split('.').next().unwrap();
    let payload = token.split('.').nth(1).unwrap();
    let signature = token.split('.').nth(2).unwrap();
    println!("header part: {header}");
    println!("payload part: {payload}");
    println!("signature part: {signature}");
}

Run it with:

cargo run --example claims_demo

The claims print as one line of JSON, with the field names as the keys:

claims as JSON:
{"sub":1,"role":"user","exp":1794648154}

The token prints as three parts separated by dots. Your expiry number and signature will differ from the ones below, because they depend on the time you run the program, but the shape is always the same:

token: <redacted>
header part: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9
payload part: eyJzdWIiOjEsInJvbGUiOiJ1c2VyIiwiZXhwIjoxNzk0NjQ4MTU0fQ
signature part: Yytn5--kvv7H5_OXXodlwtqRzwdK_UcbdF5Wt9WbmYc

The payload part is the claims JSON, encoded, and the signature part is the proof that the payload was signed by the holder of the secret. The next section decodes both readable parts to show exactly what they hold.

Working Setup:

If the demo prints the claims as {"sub":1,"role":"user","exp":1794648154} and then a token with three dot-separated parts, the struct is wired up correctly. The JSON line is the payload, and the token is that same JSON signed.

Reading the Token Apart

A token has three parts, separated by two dots. The first part is the header, the second is the payload, and the third is the signature. The header and the payload are encoded, not encrypted, which means anyone can decode them and read what they say. Only the signature needs the secret, and only the signature proves the token is genuine.

Decode the header part from the token above. The encoding is base64url, a way of writing bytes as text using letters, digits, a hyphen, and an underscore, with no padding characters at the end. Python can decode it from the terminal:

echo "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9" | python3 -c "import sys,base64; s=sys.stdin.read().strip(); print(base64.urlsafe_b64decode(s + '='*(-len(s)%4)).decode())"
{"typ":"JWT","alg":"HS256"}

The header says the token is a JWT, a JSON Web Token, and that it was signed with HS256. HS256 is a signing method that combines a hash function with a shared secret, and it is the default algorithm in the jsonwebtoken crate. The header is built by the crate, not by the app, and the app never changes it.

Decode the payload part the same way:

echo "eyJzdWIiOjEsInJvbGUiOiJ1c2VyIiwiZXhwIjoxNzk0NjQ4MTU0fQ" | python3 -c "import sys,base64; s=sys.stdin.read().strip(); print(base64.urlsafe_b64decode(s + '='*(-len(s)%4)).decode())"
{"sub":1,"role":"user","exp":1794648154}

The payload is the claims JSON, exactly as the demo printed it. Anyone holding the token can read this, including the user id and the role. That readability is by design, and it is the reason the next section draws a hard line around what may go in a claim.

The signature part does not decode to anything readable, because it is not encoded text. It is the output of the signing calculation over the header and the payload, made with the secret. The server checks a token by redoing that calculation with its own copy of the secret and comparing the result with the signature in the token. If they match, the payload was signed by someone holding the secret, and the payload has not changed since. If they do not match, the token is rejected.

Base64url Leaves the Padding Off:

A token part has no = padding characters at the end, because base64url drops them. The Python decode above adds the padding back with '='*(-len(s)%4), which computes how many = signs are needed to make the length a multiple of four. Without that step, the decode fails on most tokens, and the failure says nothing about the token itself. The padding is a property of the encoding, not of the claims.

Decoding Is Not Verifying:

Decoding the payload with base64 proves nothing about the token. Anyone can decode it, and anyone can write a new payload and encode it. Only the signature check proves the token was made by the server, and only that check may be trusted. A handler that reads the payload without verifying the signature accepts forged tokens.

The sub Claim

sub is short for subject, the thing the token is about, and here it is the user id, the id column of the users table. The login step puts the id of the row it just checked into sub, so the token names exactly one user, and no other. When the server later verifies the token, it reads sub and knows which user is asking, without touching the database.

The type is i32 because the id column is SERIAL, a 32-bit integer, and the Rust User struct holds it as i32 too. Keeping the same type in all three places means the id never changes shape as it moves from the table to the token to the handler. A token that carried the id as a string would need parsing on the way back in, and parsing is a place where mistakes hide.

The value is a plain number, not a name or an email, because a number is stable. A user can change their name or their email, and the id stays the same, so a token issued before the change still names the right user after it. The id is also meaningless on its own. Knowing that a token belongs to user 1 tells an attacker nothing about who user 1 is, unless the attacker can also read the database.

The role Claim

role is a string holding "user" or "admin", and it says what the token holder may do. A role is a named set of permissions, and this app has two of them. An ordinary user may reach their own data, and an admin may reach the admin routes too. The login step writes "user" into every token it mints, because the users table has no role column to read a role from, so every user who logs in gets the ordinary role. A token that needs the admin role has to be minted with "admin" passed in as the role, and the code that does that must decide who qualifies, which is a job for the role check that reads this claim, not for the claim itself.

The claim is a plain string rather than a number or a list, because two roles fit in one word each, and a string reads clearly in the decoded payload. A reader who decodes the token sees "role": "user" and knows at once what it means. The string is also what the later check compares against, with a plain equality test, so there is no mapping step where a number could mean the wrong role.

One consequence deserves a plain sentence. The role travels inside the token, and the token is signed, so the role cannot be changed without breaking the signature. A client who edits the payload to say "admin" produces a token whose signature no longer matches, and the server rejects it. The signature is what makes the role trustworthy, not the claim on its own.

The exp Claim

exp is short for expiry, and it holds the time after which the token must not be accepted, as seconds since the Unix epoch. The Unix epoch is midnight on 1 January 1970, and counting seconds from it is how computers write a point in time as one number. The login step sets exp to the current time plus 3600 seconds, which is one hour, so a token minted at noon stops working at 1 pm.

The type is usize, an unsigned integer, because a time in seconds is never negative, and the jsonwebtoken crate requires the expiry to be a number. The crate also requires the claim to be present: its default validation refuses a token with no exp at all, so a token that forgets its expiry is rejected rather than treated as never expiring. That default is a safety net. A token with no expiry would work forever, and a stolen one would never stop working.

The expiry is the only claim the server checks against the clock. When a token arrives, the crate compares exp with the current time, and if the current time has passed it, the token is rejected. The comparison allows a small leeway of 60 seconds for clock differences between machines, so a token that expired a few seconds ago may still pass, and a token whose expiry is more than a minute in the past never does. Tests that check expiry use an expiry a full hour in the past, so the leeway cannot hide the result.

What Must Never Go in a Claim

The payload is readable by anyone who holds the token, so a claim must never hold anything the holder should not see. A password is the clearest case: putting the password in a claim would hand it to anyone who reads the token, and tokens travel in headers, in logs, and in browser storage, where many eyes can reach them. An email is a smaller case of the same rule. It is not a secret in the same way, but it is personal data, and a token that carries it spreads that data everywhere the token goes.

The rule is to carry identity and permission, and nothing else. The user id names the user, the role names what the user may do, and the expiry names when the token stops working. Those three are enough for the server to decide every request, and none of them is a secret. If a handler needs more about the user, such as the name or the email, it reads the row from the database using the id from sub, instead of stuffing the data into the token. The database lookup costs one query, and it keeps personal data out of a value that travels the network on every request.

A Token Is Not Encrypted:

The payload is encoded with base64url, which anyone can reverse in one command, as the decode above shows. Encoding is not encryption, and it hides nothing. Treat every claim as public text. If a value must stay secret, it does not belong in a token at all.

The Concept Behind Claims

A claim is a statement the issuer makes about the subject, and the signature is the issuer standing behind that statement. The server signs the statement "user 1 has role user until this time", and anyone who verifies the signature knows the server really said it. The three claims are three statements: this token is about user 1, that user is an ordinary user, and the statement holds until the expiry time.

That shape is why a token can replace a server-side session. A session id says nothing on its own, and the server must look it up to learn anything. A token says everything the server needs, and the signature proves the server said it, so the server can trust the token without a lookup. The price is that the statements cannot change after the token is made. A role change or a password change does not reach a token that is already out in the world, and the token keeps working with its old statements until it expires. The one-hour expiry is what keeps that price small.

A beginner can think of claims as the writing on a signed letter. The letter says who it is for, what the bearer may do, and until when, and the signature at the bottom proves who wrote it. The letter can be read by anyone who holds it, and the writing cannot be altered without breaking the seal. The server writes the letter at login, the client carries it, and the server reads it back and checks the seal on every request.

A Richer Complete Example

Two tokens minted for two different users show how little changes between them. The demo below mints one token for user 1 and one for user 2, with the same secret, and prints both payloads decoded. Only the sub value differs, because the role and the expiry are the same for both.

examples/claims_demo.rs
use axum_project::auth::create_token;

fn main() {
    let first = create_token(1, "user", "test-secret-only-for-local-development").unwrap();
    let second = create_token(2, "user", "test-secret-only-for-local-development").unwrap();
    println!("first token: {first}");
    println!("second token: {second}");
}

Run it with:

cargo run --example claims_demo

The two tokens are different strings, because the payloads differ in one number, and a different payload makes a different signature. Decoding the payload part of each shows the difference plainly: one says "sub": 1 and the other says "sub": 2. Everything else, the role and the expiry hour, matches. That is the whole point of sub. It is the one claim that tells tokens apart, and it is the one the server reads to know who is asking.

An admin token shows the role claim doing its job. Mint one with the role "admin" and decode its payload:

examples/claims_demo.rs
use axum_project::auth::create_token;

fn main() {
    let admin = create_token(1, "admin", "test-secret-only-for-local-development").unwrap();
    println!("admin token: {admin}");
}

The decoded payload reads {"sub":1,"role":"admin","exp":1794648154}, with the same shape and a different role word. The structure never changes, only the values inside it. A handler that reads the role claim sees "admin" and can allow the request, and a handler that reads it on an ordinary token sees "user" and refuses. The claim carries the decision, and the signature makes the decision trustworthy.

A Plain Text Diagram of the Token

The token is three parts, and each part has one job.

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9
        .eyJzdWIiOjEsInJvbGUiOiJ1c2VyIiwiZXhwIjoxNzk0NjQ4MTU0fQ
        .Yytn5--kvv7H5_OXXodlwtqRzwdK_UcbdF5Wt9WbmYc
        |                                  |                                   |
        v                                  v                                   v
header: {"typ":"JWT",                payload: {"sub":1,                    signature: proof made
          "alg":"HS256"}                       "role":"user",                         with the secret
                                                "exp":1794648154}                    over header + payload

The header names the signing method, the payload carries the three claims, and the signature proves both were written by the holder of the secret. A reader can decode the first two parts with no secret at all, and the third part is the only one that needs it.

Testing It

The tests below mint tokens and check what is inside them, without starting a server. They use the same create_token helper the login step uses, and they decode the token with the matching verify helper to prove the claims round-trip: what goes in at minting is what comes out at verification.

tests/jwt_test.rs
use axum_project::auth::{Claims, create_token, verify_token};

const SECRET: &str = "test-secret-only-for-local-development";

#[test]
fn claims_round_trip_through_a_token() {
    let token = create_token(1, "user", SECRET).unwrap();
    let claims = verify_token(&token, SECRET).unwrap();
    assert_eq!(claims.sub, 1);
    assert_eq!(claims.role, "user");
    assert!(claims.exp > 1_700_000_000);
}

#[test]
fn admin_role_survives_the_round_trip() {
    let token = create_token(1, "admin", SECRET).unwrap();
    let claims = verify_token(&token, SECRET).unwrap();
    assert_eq!(claims.role, "admin");
}

#[test]
fn two_users_get_different_tokens() {
    let first = create_token(1, "user", SECRET).unwrap();
    let second = create_token(2, "user", SECRET).unwrap();
    assert_ne!(first, second);
    let first_claims = verify_token(&first, SECRET).unwrap();
    let second_claims = verify_token(&second, SECRET).unwrap();
    assert_eq!(first_claims.sub, 1);
    assert_eq!(second_claims.sub, 2);
}

The first test mints a token and verifies it, then checks each claim in turn. The expiry assertion only checks that the value is a large number, a time in the current era, because the exact expiry depends on when the test runs. The second test proves the role string survives the trip. The third test proves two users get two different tokens, and that each token decodes to its own user id. Run them with:

cargo test --test jwt_test -- --test-threads=1
test admin_role_survives_the_round_trip ... ok
test claims_round_trip_through_a_token ... ok
test two_users_get_different_tokens ... ok

Common Beginner Mistakes

Putting the password in a claim

// Wrong - the payload is readable by anyone holding the token
#[derive(Debug, Serialize, Deserialize)]
pub struct Claims {
    pub sub: i32,
    pub role: String,
    pub exp: usize,
    pub password: String,
}

A claim that holds the password hands the password to the client, to every log the token passes through, and to anyone the client forwards the token to. The fix is to leave the field out entirely. The server checks the password once at login, and after that the token proves the check already happened. The password never needs to travel again.

Leaving exp out of the struct

// Wrong - a token with no expiry is rejected by the default validation
#[derive(Debug, Serialize, Deserialize)]
pub struct Claims {
    pub sub: i32,
    pub role: String,
}

The default validation requires the exp claim to be present, so a token minted from this struct fails verification with a missing-claim error. The fix is to keep exp in the struct and set it at minting time. An expiry is not optional decoration. It is the mechanism that bounds the damage when a token leaks.

Using a string for sub

// Wrong - the id is a number in the database, and parsing it back invites mistakes
#[derive(Debug, Serialize, Deserialize)]
pub struct Claims {
    pub sub: String,
    pub role: String,
    pub exp: usize,
}

A string sub forces every reader to parse the text back into a number before it can look the user up, and a token that carries "abc" instead of a number would fail that parse at verification time, or worse, pass it in one place and fail it in another. The fix is the i32 type, which matches the database column and the Rust struct, so the id moves between them with no conversion at all.

Trusting a decoded payload without verifying

// Wrong - decoding reads the payload, and it proves nothing
let payload = token.split('.').nth(1).unwrap();
let claims: Claims = serde_json::from_slice(&decoded_payload).unwrap();

This code reads the claims out of a token nobody verified. Anyone can write a payload that says "sub": 1, "role": "admin", encode it, and hand it to this code, and the code would believe it. The fix is to call the verify helper, which checks the signature and the expiry before it returns the claims. Decoding is for learning and debugging. Verification is for deciding.

Final Complete Example

Here is everything from this page put together: the struct, the expiry helper, and the minting function that turns claims into a token.

src/auth.rs
use std::time::{SystemTime, UNIX_EPOCH};

use jsonwebtoken::{EncodingKey, Header, encode};
use serde::{Deserialize, Serialize};

use crate::errors::AppError;

#[derive(Debug, Serialize, Deserialize)]
pub struct Claims {
    pub sub: i32,
    pub role: String,
    pub exp: usize,
}

fn expiry_in_one_hour() -> usize {
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .expect("system time is before the Unix epoch")
        .as_secs() as usize;
    now + 3600
}

pub fn create_token(user_id: i32, role: &str, secret: &str) -> Result<String, AppError> {
    let claims = Claims {
        sub: user_id,
        role: role.to_string(),
        exp: expiry_in_one_hour(),
    };
    let key = EncodingKey::from_secret(secret.as_bytes()).map_err(|error| {
        eprintln!("encoding key error: {error}");
        AppError::InternalError
    })?;
    encode(&Header::default(), &claims, &key).map_err(|error| {
        eprintln!("token encode error: {error}");
        AppError::InternalError
    })
}
examples/claims_demo.rs
use axum_project::auth::{Claims, create_token};

fn main() {
    let claims = Claims {
        sub: 1,
        role: "user".to_string(),
        exp: 1794648154,
    };
    println!("claims as JSON:");
    println!("{}", serde_json::to_string(&claims).unwrap());
    let token = create_token(1, "user", "test-secret-only-for-local-development").unwrap();
    println!("token:");
    println!("{token}");
}

Run the checks with these commands:

cargo check
cargo test --test jwt_test
cargo run --example claims_demo

Summary

The three claims are a division of labour. sub answers who is asking, role answers what that user may do, and exp answers until when the answer holds. Together they are everything the server needs to decide a request, and they are the only things a token may carry, because everything in a token is readable by its holder. The signature is what turns those three statements from plain text into a trustworthy credential, and the expiry is what bounds the damage when a token falls into the wrong hands.

The framework to carry forward is a question to ask about any new field before adding it to the struct. Would it be safe if the client read it, printed it, and forwarded it to a stranger? If the answer is no, the field belongs in the database, reached through the id in sub, not in the token. If the answer is yes, and the field changes how the server decides a request, it may earn its place beside the three already here. The next step is the other half of the token: the secret that signs these claims, and where it must live so the signature stays trustworthy.