11 Jun 2018

JWT: how token is created

In this post i am going to give a thoughts about how JWT token is got created. If do not aware of JWT token and its use-cases then please read this and come back.


Ok, now you have basic introduction about JWT token so i can go ahead of steps that involves creating token.

Let say we are creating token with followings:

algorithm is HS384
payload is {'some': 'payload'}
secret key is "secret"
and
header is {"custom_header": "custom_val"}


So lets follow through the creation of JWT token.

 1. algorithm is checked if it is a supported or not.

2. payload is encoded in utf-8 and converted into a byte string.
     b_payload = b'{"some":"payload"}'


3. header is encoded in utf-8 and converted into a byte string.
    b_header = b'{"typ":"JWT", "alg":"HS384", "custom_header": "custom_val"}'

4. b_payload is encoded into a base64 encoding:
    en_payload = base64_encode(b_payload)
    looks like
    b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzM4NCIsImhrIjoiaGVhZC12YWwifQ'

5. b_header is encoded into a base64 encoding
    en_header = base64_encode(b_header)
    looks like
    b'eyJzb21lIjoicGF5bG9hZCJ9'

6.  A signing string is created by concatenating en_payload and en_header with dot (.)
    signing_input = b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzM4NCIsImhrIjoiaGVhZC12YWwifQ' .b'eyJzb21lIjoicGF5bG9hZCJ9'

7. signature is created by signing an algorithm with signing_input and key
    signature = sign(signing_input, key)     # alg_obj is an algorithm object
    looks like
    b'\xc1\x7f\x7f\xfb\x96\xb3\x0fc\x1e\x84.\x02\xe5\xf5\xfd\xbb\xb2\x9bf0\x9ea\xec\x06U\x15-]\xca;\x1f\xfb\xa6J\xc7pv\xdf\x0cu;j`o\xa6ia\x9d'

8. Now, signature is encoded into a base64 encoding
   en_signature = base64_encode(signature)
   looks like
   en_sign = b'wX9_-5azD2MehC4C5fX9u7KbZjCeYewGVRUtXco7H_umSsdwdt8MdTtqYG-maWGd'

9. And finally all three components, en_payload , en_header and en_signature,  are concatenated by with dot (.) which results in token
   looks like
 b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzM4NCIsImhrIjoiaGVhZC12YWwifQ.eyJzb21lIjoicGF5bG9hZCJ9.wX9_-5azD2MehC4C5fX9u7KbZjCeYewGVRUtXco7H_umSsdwdt8MdTtqYG-maWGd'


This is very basic of how token is created,  hope you find it useful.

No comments:

Post a Comment