All you need to know about JSON Web Tokens(JWT) — Part 2/2

Kanika Modi
3 min readMar 31, 2020

In the first part of this JWT blog, I talked about what JSON Web Tokens are, how they work and when to use them. If you haven’t checked that out, I’d recommend you to go through Part 1 first. In this part, I’ll be talking about the structure of JWT and how a server can verify and issue JWT token in Javascript.

JWT Structure

Every JWT has the same structure. There are three parts separated by a period: Header, Payload, Signature. Each section is composed of base64url-encoded JSON containing specific information for that token. Simply put, a JWT is just a string with the following format:

const jwtToken = base64urlEncoding(header) + ‘.’ + base64urlEncoding(payload) + ‘.’ + base64urlEncoding(signature)
Sample JWT

Header

Header is used to identify the type of token and which algorithm is used to generate the signature. Here, HS256 indicates that this token is signed using HMAC-SHA256. Typical cryptographic algorithms used are HMAC with SHA-256 (HS256) and RSA signature with SHA-256 (RS256). JWA (JSON Web Algorithms) RFC 7518 introduces many more for both authentication and encryption.

{
“algorithm” : “HS256”,
“type” : “JWT”
}

Payload

Payload contains a set of claims about the user and metadata. There are three types of claims: reserved, public, and private claims.

  1. Reserved claims: universally predefined claims like issuer, expiration time, subject, audience etc.
  2. Public claims: unique as no two public claims can be same, to avoid collisions they are usually defined in the IANA JSON Web Token Registry.
  3. Private claims: custom claims agreed upon by both parties using them.
{
“loginRole” : “admin”,
“exp” : 1422654638
}

Signature

JSON Web Signature (JWS) securely validates the user and checks if the message wasn’t changed. The final token string is placed under a cryptographic algorithm specified in the header, in this case HMAC-SHA256.

HMAC-SHA256(
base64urlEncoding(header) + ‘.’ +
base64urlEncoding(payload),
secret
)

Verify & Issue JWT

For this section, I will create a JWT token and save it in session cookie in Javascript. Install the jsonwebtoken and the cookie library for the same. Tokens can also be generated independent of cookies.

$ npm install jsonwebtoken
$ npm install cookie

To use this library, use require statements:

const jwt = require(“jsonwebtoken”);
const cookie = require(‘cookie’);

Now to see cookies that have been set and verify JWT session in this cookie, use following code:

const getCookies = function(event) {if(event.headers && (event.headers.cookie || event.headers.Cookie)) {
return cookie.parse(event.headers.cookie || event.headers.Cookie);
}
return {}
}const verifySession = function(event) {var token = getCookies(event)[CookieName]
if(token){
return jwt.verify(token, key);
}
return false;
}

To generate JWT token cookie, use following code:

const generateTokenCookie = function(event, response) {response.headers = response.headers || {};
var sessionCookies = getCookies(event)[CookieName];
if(!sessionCookies) {
var payload = {userId: event.headers[‘X-FORWARDED-USER’]};
var token = jwt.sign(payload, key, {expiresIn: 24 + ‘h’});
var date = new Date();
date.setTime(date.getTime() + (24 * 60 * 1000););
var jwtCookie = cookie.serialize(CookieName, token, {
path: “/”,
expires: date,
httpOnly: true,
secure: true
});
response.headers[“setCookie”] = jwtCookie;
}
}

I hope this two-part blog explains JSON Web Token (JWT) and how it is a powerful tool for confidently transmitting data between two parties through tokens.

Thank you for reading! If you found this helpful, here are some next steps you can take:

  1. Check out Part 1 of this blog!
  2. Send some claps my way!
  3. Follow me on Medium and connect with me on LinkedIn!
  4. Check out jwt.io! This is a specialized website about JWT with tools and documentation, maintained by Auth0.
  5. Use JSON Validator to validate JSON Web Token

--

--

Kanika Modi

Software Engineer @amazon | Designing Systems At Scale | Tech & Career Blogs | She/Her | ViewsMine()