Logic of the JWT(JSON Web Tokens)

By | January 27, 2019

In this post, we will learn what is the JWT and logic of the JWT. The IETF is designed as a standard token format. Such as validation, user identification, data integrity and information security each other multiple points.

JWT consists of 3 separate JSON pieces encoded in Base64 format. The pieces are separated by a dot (.) symbol and represent the JWT as a whole. As i said, there are 3 fields. They are JOSE Header, Payload and Signature.

JOSE Header

JWT header information is written in JSON format and standard fields are found. You can see an example in the following.

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

Alg means, “Specifies the cryptotic algorithm to be used to protect data integrity.” and typ means, “Defined a JWT object”.

When the JOSE header is enclosed in the token, it is encoded in Base64 format. For example, the Base64 counterpart of the above JSON heading is eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9. The URL-friendliness of JWT is due to its use of Base64 notation.

Payload

A JWT token should be unique between a token producer and a consumer. This uniqueness defines the payload or other claim information. The payload can include fields such as user ID, timeout, and user authority.

{
  "id": "12345",
  "name": "Mert Simsek",
  "scopes": [
      "email",
      "page"
   ]
}

For instance, it needs to be a field like id to represent belonging. There are standarts for it but it is not mandatory.

Signature

The last piece of the JWT, which consists of three parts, is the JWT signature. The signature part guarantees data integrity between the token manufacturer and the consumer. When creating the signature, the algorithm defined in the JOSE heading is used.

As long as, we try to create a JWT with PHP, it will be as below.

$header = base64_encode("HEADER");

$payload = base64_encode("PAYLOAD");

$mixed = $header + "." + $payload;

$secretKey = "My_Secret_Key";

$signature = base64_encode(hash_hmac('sha256', $mixed, $secretKey);

$jwtToken = $mixed + "." + $signature;

As a result of the above operations, our JWT token output will be. You can check the generated JWT information on https://jwt.io/.

That’s it, in this article, so much for now. We have learned logic of JWT.