JWT, JWE, and JWKS Explained: A Developer’s Guide to Token-Based Security

🧠 What is JWT?

JWT (JSON Web Token) is a compact, URL-safe token format used to transmit claims securely between parties. It’s the backbone of stateless authentication and is often signed using JWS (JSON Web Signature) or encrypted using JWE (JSON Web Encryption).

πŸ”‘ JWT = Header + Payload + Signature

eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.
eyJ1c2VySWQiOiIxMjM0Iiwicm9sZSI6InVzZXIifQ.
ZHVtbXktc2lnbmF0dXJl
SectionPurpose
HeaderMetadata (algorithm, type)
PayloadClaims (e.g., userId, role)
SignatureVerifies token integrity

βœ… JWT (JWS) – Signed Token

JWS = JSON Web Signature
It’s the most common JWT. The payload is not encrypted β€” just signed to ensure authenticity.

πŸ“Œ Use Case:

  • User login tokens

  • API access tokens

  • OAuth2 flows

πŸ” JWE – Encrypted JWT

JWE = JSON Web Encryption
Unlike JWS, JWE encrypts the payload so it’s not visible to intermediaries. It includes more sections than JWS.

<Header>.<EncryptedKey>.<IV>.<Ciphertext>.<AuthTag>
ComponentDescription
HeaderAlgorithm & encryption method
Encrypted KeyEncrypted symmetric key using RSA
IVInitialization Vector
CiphertextEncrypted payload
AuthTagAuth tag for integrity/authentication

πŸ“Œ Use Case:

  • Financial data

  • Healthcare apps

  • B2B confidential communication

πŸ”„ JWT vs JWE

FeatureJWS (Signed) πŸ”JWE (Encrypted) πŸ”
Payload Visibleβœ… Yes❌ No
Integrityβœ… Ensured via signatureβœ… Ensured via encryption
Confidentiality❌ Not secureβœ… Encrypted
Use CaseAuth tokensSensitive data transfer

🧩 What is JWKS?

JWKS = JSON Web Key Set
It’s a public endpoint that exposes public keys in a JSON format. It's how services like Auth0, Google, and Okta let you verify JWTs without sharing the private key.

🧠 JWKS provides a way to rotate keys without breaking consumers.

πŸ“Œ URL Example:

https://your-auth-server.com/.well-known/jwks.json

πŸ“„ Example Response:

{
  "keys": [
    {
      "kty": "RSA",
      "kid": "abc123",
      "use": "sig",
      "n": "...base64url...",
      "e": "AQAB"
    }
  ]
}

πŸ—‚οΈ How it All Works Together

sequenceDiagram
    participant AuthServer as πŸ” Auth Server
    participant JWKS as 🌍 JWKS Endpoint
    participant ClientApp as πŸ§‘ Client App
    participant API as 🟒 API Server

    ClientApp ->> AuthServer: πŸ” Authenticate (Login)
    AuthServer -->> ClientApp: ⏎ JWT (Signed or Encrypted)

    ClientApp ->> API: πŸ“¨ Send JWT in Authorization Header
    API ->> JWKS: πŸ” Fetch Public Keys
    JWKS -->> API: πŸ“₯ Return Key Set
    API ->> API: βœ… Verify Signature using Public Key
    API -->> ClientApp: πŸ”“ Return Protected Data

πŸ› οΈ Verifying JWTs with JWKS in Node.js

βœ… Install Dependencies

npm install jwks-rsa jsonwebtoken express

πŸ”§ Verify JWT with JWKS

const jwt = require("jsonwebtoken");
const jwksClient = require("jwks-rsa");

const client = jwksClient({
  jwksUri: "https://your-auth-server.com/.well-known/jwks.json"
});

function getKey(header, callback) {
  client.getSigningKey(header.kid, (err, key) => {
    const signingKey = key.getPublicKey();
    callback(null, signingKey);
  });
}

function verifyToken(token) {
  jwt.verify(token, getKey, {
    algorithms: ["RS256"]
  }, (err, decoded) => {
    if (err) return console.error("❌ Invalid Token");
    console.log("βœ… Verified Token Payload:", decoded);
  });
}

βœ… Best Practices

PracticeWhy It Matters
Use RS256 (asymmetric) for signingSafer than HMAC in distributed systems
Always verify iss, aud, expProtect against spoofed/expired tokens
Enable key rotation using JWKSImproves security without breaking apps
Use JWE only when confidentiality is requiredSaves performance otherwise

πŸš€ Final Thoughts

JWTs are everywhere β€” but understanding the difference between JWS, JWE, and JWKS is key to building secure, scalable, and standards-compliant systems.

βœ… Use JWS for API authentication
βœ… Use JWE for encrypting sensitive data
βœ… Use JWKS for secure key distribution and rotation

Let me know if you'd like a follow-up tutorial to implement JWKS-based auth with Auth0, Google Identity, or AWS Cognito! πŸ‘‡


About Me πŸ‘¨β€πŸ’»

I'm Faiz A. Farooqui. Software Engineer from Bengaluru, India.
Find out more about me @ faizahmed.in

3
Subscribe to my newsletter

Read articles from Faiz Ahmed Farooqui directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Faiz Ahmed Farooqui
Faiz Ahmed Farooqui

Principal Technical Consultant at GeekyAnts. Bootstrapping our own Data Centre services. I lead the development and management of innovative software products and frameworks at GeekyAnts, leveraging a wide range of technologies including OpenStack, Postgres, MySQL, GraphQL, Docker, Redis, API Gateway, Dapr, NodeJS, NextJS, and Laravel (PHP). With over 9 years of hands-on experience, I specialize in agile software development, CI/CD implementation, security, scaling, design, architecture, and cloud infrastructure. My expertise extends to Metal as a Service (MaaS), Unattended OS Installation, OpenStack Cloud, Data Centre Automation & Management, and proficiency in utilizing tools like OpenNebula, Firecracker, FirecrackerContainerD, Qemu, and OpenVSwitch. I guide and mentor a team of engineers, ensuring we meet our goals while fostering strong relationships with internal and external stakeholders. I contribute to various open-source projects on GitHub and share industry and technology insights on my blog at blog.faizahmed.in. I hold an Engineer's Degree in Computer Science and Engineering from Raj Kumar Goel Engineering College and have multiple relevant certifications showcased on my LinkedIn skill badges.