What is a JWT or JWS token? (Json web signed token)

About

json web token is a access token.

It's also known as jot.

When a JWT is signed, it becomes a JWS and can be used for sender authentication and authorization.

The main purpose of JWTs is to transfer claims (ie identity property) between two parties

This is a simple, optionally validated and/or encrypted, container format.

Because the token is signed and contains property, it is not necessary for the recipient to call a server to validate the token or obtain additional information.

The data format is JSON.

JWTs, like any other client-side data, can be stored as cookies

Usage

  • to support:
    • server-to-server.
    • multiple party communication (three or more parties involved in a request) The client connects, pass the JWT, the server passes the JWT to another server
    • or client-to-server communication
  • to avoid database lookup
  • federation. (single sign-on and OpenID Connect)

Format

JWT is constructed from three different parts:

  • the header,
  • the payload,
  • and the signature.

Encoded

Encoded, JWT is a compact, printable representation of data, along with a signature to verify its authenticity (and therefore perform authentication)

These three parts are encoded separately and a JWT encoded looks like:

Header.Payload.Signature
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.
TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

where:

  • The Header is Base64Url encoded
  • The payload is Base64Url encoded

Decoded

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

where:

  • alg: the hashing algorithm such as HMAC SHA256 or RSA. (used for signature). Use the kid instead.
  • typ: the media type of the JWT itself
  • kid: holds a key identifier.
    • to look up the corresponding algorithm and not make it public
    • when you have multiple keys to sign the tokens and you need to look up the right one to verify the signature.

Payload

ie user data

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

where the property are known as claims

  • sub is a case-sensitive string or URI that uniquely identifies the party that this JWT carries information about (rowId)
Claims

Claims are just the JSON properties of the payload

There are three types of claims:

  • reserved (predefined claims)
  • public, (known and defined by everybody in a registration repository (ie IANA)
  • and private claims

JWTs carry certain common fields such as:

See:

Signature

signature to verify the identify and the payload integrity.

When a JWT is signed, it becomes a JWS (rfc7515)

Example with HMAC SHA256 hashing algorithm if defined in the header

HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  secret)

Application

Authentication / Authorization

JWS can be used for sender authentication because it's signed. A JSON Web Token will be returned when a user successfully logs in using their credentials.

It can be sent:

(Authorization)

Whenever the user wants to access a protected route, it should send the JWT Therefore the content of the header should look like the following.

Authorization: Bearer <token>

The server’s protected routes will check for a valid JWT in the Authorization header; if there is, the user will be allowed.

As JWTs are self-contained, all the necessary information is there, reducing the need of going back and forward to the database.

Jwt Auth Flow

Other

Example

Several

  • One JWT for the ID token, a token that carries the user’s profile information, useful for the UI.
  • One JWT for interacting with the API backend (the access token).
  • One JWT for our client-side state: the shopping cart.

Operation

Signing

signing them, using JSON Web Signatures (JWS,RFC 75156),

The default signature method for JWT’s is known as HS256. HS stands in this case for HMAC Signature using SHA256.

RS256

RS256 (RSA Signature with SHA-256) is an private/public key algorithm (ie asymmetric)

  • The signing server has the private key used to generate the signature,
  • The consumer of the JWT retrieves a public key (from https://example.com/.well-known/jwks.json) and uses it to validate the JWT signature.

Multiple keys can be found in the JWKS when rotating signing certificates.

HS256

HS256 (HMAC with SHA-256) is a symmetric algorithm. This private key (or secret) is created when the application is registered.

Encryption

Encrypting them, using JSON Web Encryption (JWE, RFC 75167).

Token verification

The frontend does not check the signature, it simply decodes the JWT so it can display its contents.

The actual checks are performed by the backend where all JWTs are verified (ie the token is decoded and the signature is verified)

You can debug at http://jwt.io/.

Example with express code: When items are added, the backend constructs a new JWT with the new item in it and a new signature

function cartValidator(req, res, next) {
    if(!req.cookies.cart) {
        req.cart = { items: [] };
    } else {
        try {
            req.cart = {
                items: jwt.verify(req.cookies.cart, process.env.AUTH0_CART_SECRET, cartVerifyJwtOptions).items
            };
       } catch(e) {
        req.cart = { items: [] };
       }
    }
    next();
}

Decode

Decoding is extracting the payload.

function populateCart() {
    const cartElem = $('#cart');
    cartElem.empty();
    const cartToken = Cookies.get('cart');
    if(!cartToken) {
       return;
    }
    const cart = jwt_decode(cartToken).items;
    cart.forEach(itemId => {
         const name = items.find(item => item.id == itemId).name;
         cartElem.append(`<li>${name}</li>`);
   });
}
function parseJwt (token) {
    var base64Url = token.split('.')[1];
    var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
    var jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    }).join(''));

    return JSON.parse(jsonPayload);
};

Security Consideration

Signature Stripping

Because the signature is encoded separately, it is possible to remove the signature and then change the header to claim the JWT is unsigned.

If the application consider unsigned JWTs valid, an attacker may modify the payload (for instance, to set the user role to root).

Be sure to consider valid only signed JWT.

Documentation / Reference





Discover More
Card Puncher Data Processing
Aws - Security Token Service (STS)

The AWS Security Token Service (STS) is a web service that enables you to request temporary limited-privilege credentials for: AWS Identity and Access Management (IAM) users or for users that you...
Browser - Storage (Client Side Data)

This page is client side data (ie stateless session) in the browser. cookie local storage WebStorage - name/value pairs - Method of storing data locally...
Oauth
In OAuth, what is the state query parameter known as Local State?

The state query parameter is an opaque value used by the client (app) in redirection flow to maintain the state between the and (response) (ie to restore or continue the navigation of the user). ...
What are JSON Web Keys (Jwk)?

A JSON Web Key (Jwk) represents a key as a JSON object. These JSON documents are provided by an identity provider server like Google, Microsoft, etc…​ but you can also generate your keys: ...
Public Key Crypto Pair Key Creation
What is a Digital Signature? (Signing in Cryptography)

A digital signature is: a hash of a message created with a secret Digital signature schemes are used for: sender authentication (no one can impersonate the sender, it proves that the message...
Oauth
What is a Oauth Access Token?

This page talks access token in the context of the OAuth specification. An access token is a token representing an access authorization created during: a implicit grant flow or a authorization code...
What is a Session Identifier?

A session identifier is a nonce that represents uniquely a session. Instead of storing session information (such as username, login, start time, ...) directly, the server creates a nonce and sends it...
What is a Session? (authentication, tracking)

A session is used in authentication in order to store the identification data. After a user has been authenticated, the identification (the user name generally) is stored in the session and other requests...
What is an access token?

A token is a authentication material An access token is a token (string) representing an access authorization. It is equivalent to a session identifier in format. It's a token that serves as delegation-specific...
Oauth
What is the Bearer Token in OAuth?

bearer token is a oauth access token implementation defined in the OAuth 2.0 Authorization Framework Bearer Tokens are the predominant type of access token used with OAuth 2.0. This is a stateless...



Share this page:
Follow us:
Task Runner