simple_jwt

JSON Web Tokens for Eiffel

Features

Quick Start

Installation

Add to your ECF:

<library name="simple_jwt" location="$SIMPLE_JWT\simple_jwt.ecf"/>

Dependencies (automatically included):

Create a Token

local
    jwt: SIMPLE_JWT
    token: STRING
do
    create jwt.make ("your-secret-key")

    -- Simple token with subject and expiration
    token := jwt.create_token_with_claims (
        "user@example.com",  -- subject
        "my-application",    -- issuer
        3600,                -- expires in 1 hour
        Void                 -- no custom claims
    )
    -- Result: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
end

Verify a Token

local
    jwt: SIMPLE_JWT
do
    create jwt.make ("your-secret-key")

    -- Check signature only
    if jwt.verify (token) then
        print ("Valid signature%N")
    end

    -- Check signature AND expiration
    if jwt.verify_with_expiration (token) then
        print ("Valid and not expired%N")
    end
end

Decode Claims

local
    jwt: SIMPLE_JWT
    subject: detachable STRING
    user_id: INTEGER_64
do
    create jwt.make ("secret")

    -- Get string claim
    subject := jwt.get_string_claim (token, "sub")

    -- Get integer claim
    user_id := jwt.get_integer_claim (token, "user_id")

    -- Get full claims object
    if attached jwt.decode_claims (token) as claims then
        -- Access any claim
    end
end

Custom Claims

local
    jwt: SIMPLE_JWT
    custom: JSON_OBJECT
    token: STRING
do
    create jwt.make ("secret")
    create custom.make_empty
    custom.put_string ("admin", "role")
    custom.put_integer (12345, "user_id")
    custom.put_boolean (True, "verified")

    token := jwt.create_token_with_claims (
        "admin@example.com",
        "my-app",
        7200,    -- 2 hours
        custom   -- custom claims merged in
    )
end

JWT Structure

A JWT consists of three Base64URL-encoded parts separated by dots:

header.payload.signature

Header

{"alg":"HS256","typ":"JWT"}

Payload (Claims)

Claim Name Description
subSubjectWho the token is about
issIssuerWho issued the token
iatIssued AtUnix timestamp of creation
expExpirationUnix timestamp when token expires
audAudienceIntended recipient
nbfNot BeforeToken not valid before this time
jtiJWT IDUnique token identifier

Signature

HMAC-SHA256(
    base64url(header) + "." + base64url(payload),
    secret
)

Use Cases

Security Notes

Specifications