DEV Community

Cover image for JWT
A.S.M. Habibullah Sadique
A.S.M. Habibullah Sadique

Posted on

JWT

JWT

JSON Web Token structure:
In its compact form, JSON Web Tokens consist of three parts separated by dots (.), which are:

  1. Header
  2. Payload
  3. Signature

So, a JWT typically looks like the following: xxxxxx.yyyyyy.zzzzzz

*Header: *

The header typically consists of two parts: the type of the token, which is JWT, and the signing algorithm being used, such as HMAC SHA256 or RSA.

For example:

{
    “alg”: “HS256, 
    “typ”: “JWT”
}
Enter fullscreen mode Exit fullscreen mode

Then this JSON IS Base64Url encoded to form the first part of the JWT.

*Payload: *

The second part of the token is the payload, which contains the claims. Claims are statements about an entity (typically, the user) and additional data. There are three types of claims: registered, public, and private claims.

Registered claims: These are a set of predefined claims which are not mandatory but recommended, to provide a set of useful, interoperable claims. Some of them are: iss (issuer), exp (expiration time), sub (subject), aud (audience), and others.

Public claims: These can be defined at will by those using JWTs. But to avoid collisions they should be defined in the IANA JSON Web Token Registry or be defined as a URI that contains a collision resistant namespace.

Private claims: These are the custom claims created to share information between parties that agree on using them and are neither registered or public claims.

An example payload could be:

{
    “sub”: “131242134”,
    “name”: “Sadique Habibullah”,
    “admin”: true
}
Enter fullscreen mode Exit fullscreen mode

The payload is then Base64Url encoded to form the second part of the JSON Web Token.

*Signature: *

To create the signature part you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that.

For example if you want to use the HMAC SHA256 algorithm, the signature will be created in the following way:

HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  secret)
Enter fullscreen mode Exit fullscreen mode

The signature is used to verify the message wasn't changed along the way, and, in the case of tokens signed with a private key, it can also verify that the sender of the JWT is who it says it is.

*Putting it altogether: *

The output is three Base64-URL strings separated by dots that can be easily passed in HTML and HTTP environments, while being more compact when compared to XML-based standards such as SAML.

Finally it becomes something like this:

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImlhdCI6MTY0NDQxNzA1NCwiZXhwIjoxNjQ0NDIwNjU0fQ.GiJsRD3463h80YlAYG92UupWcot7jWRHNhnNpnBV2bQ 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)