JSON Web Token / JWT Raw Implementation in Python3

{base64_header}.{base64_payload}.{base64_signature}
  • the header describing the token type and the signing algorithm in JSON
  • the payload describing the claims or information about the user assigned the token in JSON
  • the private key that is used to sign the header and the payload
  • Removing all non-key, non-value white spaces in the JSON message
  • URL Safe Base64 encoding
  • HMAC (Keyed-Hashing for Message Authentication) operation

Functional Operations

JSON White Space Removal

import jsoncleaned_json_str = json.dumps(
json.loads(raw_json_string),
separators = (",", ":"), # default is (",", ": ") notice the space
)

Transport Safe Encoding

import base64b64_encoded_json = base64.urlsafe_b64encode(
cleaned_json_str.encode("ascii") # convert to bytes
)
# here we need to strip the offsets filled with "=" for use
#
b64_final_json = b64_encoded_json.decode("ascii").rstrip("=")

HMAC

import hmac
import hashlib
import base64
secret_key_bytes = b"my_secret_key"signature_bytes = hmac.new(
secret_key_bytes,
msg = your_message_to_sign.encode("ascii"),
digestmod = hashlib.sha256,
).digest()
b64_signature = base64.urlsafe_b64encode(
signature_bytes).decode("ascii").rstrip("=")

Inputs

Header

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

Payload

{  
"sub": "cd08769d-c6a5-43cf-be5f-14f34ecddaa2",
"name": "Your Friendly Neighbor",
"iat": 1609459200
}

Private Key

your-secret-goes-here

Bring It All Together

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Linux and Git for your everyday life…

Word2Vec for Talent Acquisition

Vi Editor (Linux) Cheat Sheeet

How Lens Saved Our Time and Created Productivity

Making a Hack’n’slash #1: Moving and following our hero

Dot progress report #1

AWS API Gateway fronting for Command and Control

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Injae Lee

Injae Lee

TODO

More from Medium

Python Card Validation Using The Luhn’s Algorithm

Working Around Memory Leaks in Your Django Application

Django models: Updating a record from a database

Full-Powered Binary Search with `bisect` in Python 3.10