In the web development world, the term JWT (Json Web Token) is widely use for security. However, i personally have little understanding about JWT and how it is useful for web security, particularly for authrization and authentication purposes. Through this writing, I am going to try to elaborate what i know about JWT and its usage.
By definition in the origin RFC, JWT is defined as:
JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is used as the payload of a JSON Web Signature (JWS) structure or as the plaintext of a JSON Web Encryption (JWE) structure, enabling the claims to be digitally signed or integrity protected with a Message Authentication Code (MAC) and/or encrypted.
So what can we grasp from this definition ? First, let's define a token. In computer programming, a token represents a single unit of meaningful information that cannot be further divided. If we incorporate the context of the web, A JWT is basically a piece of information that is unique and undivided which is used as a medium to exchange information online.
With this information, now we wonder how does a JWT looks like. For this, we can refer to JWS as the most commonly used JWT which look like this.
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNzA4MzQ1MTIzLCJleHAiOjE3MDgzNTUxMjN9.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
Lets break this out further. So the JWS is a series of strings separated by a dot(.) consisted by 3 parts:
(Header).(Payload).(Signature)
This part contains the metadata of the token, which covers the signing algorithm (e.g., HS256, RS256) and token type (usually it is always JWT). The object header then encoded into Base64Url basis.
{
"alg": "HS256",
"typ": "JWT"
}
Base64Url: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
This part is an object containing the main data being exchanged. The attributes can vary according to the needs. The object payload then also encoded into Base64Url basis.
{
"userId": 154,
"role": "admin",
"exp": 1999825319
}
Base64Url: eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNzA4MzQ1MTIzLCJleHAiOjE3MDgzNTUxMjN9
This part is an encryption of the token Header and token Payload (both in the base64Url encoded version) combined with some kind of a secret string. The encryption is done with the algorithm stated in the token Header. The token signature acts as a validation that ensures the token’s integrity and authenticity.
HMACSHA256(
base64UrlEncode(header) + "." + base64UrlEncode(payload),
secret
)
signature: SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
In a nutshell, this is how the JWT is used in the authentication process: