What is JWT?

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed using a secret key (with HMAC algorithm) or a public/private key pair using RSA or ECDSA.

JWTs consist of three parts separated by does (.):

  1. Header - contains the type of the token and the signing algorithm used
  2. Payload - contains the claims (statements about an entity and additional data).
    1. Registered Claims (iss, exp, sub, aud)
    2. Public Claims
    3. Private Claims
  3. Signature - Used to verify the message wasn’t changed along the way

A typical JWT looks like this:

xxxxxx.yyyyyy.zzzzzz

Why Consider Using JWT?

Authentication and Authorization

The primary purpose of JWT is to securely transmit information between parties. It’s particularly useful for authentication and authorization scenarios.

Statelessness

JWTs are stateless by design. The server doesn’t need to store session information as all necessary data is contained within the token itself. This makes it highly scalable for distributed systems.

graph LR
    SessionBased[Session-Based Auth] --> ServerState[Server Stores Session State]
    SessionBased --> DB[(Database Lookups)]
    
    JWT[JWT-Based Auth] --> NoServerState[No Server-Side Session Storage]
    JWT --> SelfContained[Self-Contained Token]
    
    ServerState --> Scaling[Scaling Challenges]
    NoServerState --> EasyScaling[Easy Horizontal Scaling]

Information Exchange

JWTs provide a secure way to exchange information between parties while ensuring the integrity of the data.

Pros of JWT

1. Statelessness