Daniel Escobedo

JSON Web Token Structure

Introduction
JSON Web Token Structure

JSON Web Tokens are structured like this:

Header.Payload.Signature

Each of these three parts (separated by dots) are Base64 encoded. This means they are not encrypted and can be easily read by anyone just by decoding it.

The first part of the token is the header, which is a JSON object that usually contains 2 key/value pairs:

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

The first key/value pair is the type of the token, which is JWT. The second one is the type of the hashing algorithm being used.

Payload

The second part of the token contains your data and any other information pertaining to this token (metadata). The payload is usually referred to as the claims.

The payload may look like:

{
  "sub": "1234567890",
  "name": "John Doe",
  "admin": true
}

The sub key here is a reserved claim, meaning it's part of a set of predefined claims used to provide additional information about the token. sub stands for "subject".

As of this writing, you can find the latest reserved claims here.

The name and admin keys are the public claims defined by you. This is typically the data that represents the entity (usually the user). To avoid collisions, the keys should contain a name in a namespace that enables names to be allocated in a manner such that they are highly unlikely to collide with other names..

Examples of collision-resistant namespaces include: Domain Names, Object Identifiers (OIDs) as defined in the ITU-T X.660 and X.670 Recommendation series, and Universally Unique IDentifiers (UUIDs)

The payload may also have private claims, which are names that are not registered claim names or public claim names.

Private Claim Names are subject to collision and should be used with caution.

Signature

The final part of the token is a hash of the encoded header and the encoded payload using a secret. It can be constructed similar to this:

const s = base64Encode(header)
          + "."
          + base64Encode(payload);

const signature = hashAlgHs256(s, "secret");

The signature is used to verify that the sender of the JWT is who it says it is and to ensure that the message wasn't changed along the way.

JWT

Using the previous example, JWTs can then be put together like:

const jwt = s + "." + base64Encode(signature);

You can read through the latest JWT open-standard here.

Author

Daniel Escobedo

I'm a JavaScript developer who loves to code. I'm always reading and learning new technologies and tools to better my skills and workflow.

View Comments
Next Post

Lexical Scope and Closures

Previous Post

Redux-Saga External Event Listener

Mastodon