Authentication - Jwt (Json web token)

1 - About

json web token is a token protocol.

It's also known as jot.

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

When a JWT is signed, it becomes a JWS

3 - Format

JWT is constructed from three different parts:

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

3.1 - 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

3.2 - Decoded


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

where:

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

3.2.2 - 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)
3.2.2.1 - 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:

3.2.3 - 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)

4 - Application

4.1 - Authentication / Authorization

Authentication - Http - Authorization Header (authentication entries) (Authorization)

In authentication, when the user successfully logs in using their credentials, a JSON Web Token will be returned.

Whenever the user wants to access a protected route, it should send the JWT, typically in the Authorization header using the Bearer schema. 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, and 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.

4.2 - Other

5 - Example

5.1 - 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.

6 - Operation

6.1 - 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.

6.1.1 - 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.

6.1.2 - HS256

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

6.2 - Encryption

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

6.3 - 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();
}

6.4 - 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);
};

7 - Security Consideration

7.1 - 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.

8 - Documentation / Reference


Data Science
Data Analysis
Statistics
Data Science
Linear Algebra Mathematics
Trigonometry

Powered by ComboStrap