JWT

JWT is a means of representing transfer requests between the two Client - Server parties, the information in the JWT string is formatted in JSON. In which the Token string must have 3 parts: header , payload part and signature part separated by "."

So according to the above theory, I will have a Token chain as follows:

header.payload.signature

Structure of JSON Web Token

As mentioned above JSON Web Token consists of 3 parts, separated by a dot (.):

1. Header

Will contains what type of token and encryption algorithm

{
    "typ": "JWT",
    "alg": "HS256"
}
  • “typ” (type) indicates that the object is a JWT

  • “alg” (algorithm) defines the encryption algorithm for the string as HS256

2. Payload

The payload will contain the information you want to put in the Token string such as username , userId , author , ...

{
  "user_name": "admin",
  "user_id": "1513717410",
  "authorities": "ADMIN_USER",
  "jti": "474cb37f-2c9c-44e4-8f5c-1ea5e4cc4d18"
}

Note do not put too much information in the Payload chain because it will affect the delay when the Server has to confirm a Token that is too long.

3. Signature

This signature will be generated by encrypting the header , payload with a secret key, for example:

data = base64urlEncode( header ) + "." + base64urlEncode( payload );
signature = Hash( data, secret ); 
  • base64UrlEncoder : header and payload encoding algorithm

The above code after encoding the header and payload using the base64UrlEncode algorithm, we will have the following string

// header 
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 
// payload 
eyJhdWQiOlsidGVzdGp3dHJlc291cmNlaWQiXSwidXNlcl9uYW1lIjoiYWRtaW4iLCJzY29wZSI6WyJyZWFkIiwid3JpdGUiXSwiZXhwIjoxNTEzNzE

Then encrypt the above 2 strings with secret (secret key) with the HS256 algorithm, we will have the following signature string:

9nRhBWiRoryc8fV5xRpTmw9iyJ6EM7WTGTjvCM1e36Q

Final

Combining the above 3 strings we will get a complete JWT chain

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsidGVzdGp3dHJlc291cmNlaWQiXSwidXN

Last updated