JSON Web Token(JWT) Basics
miAlism / January 15, 2022
2 min read •
JSON Web token(JWT) is an open standard which defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.
JWT consist of three parts separated by dots(.): Header, Payload and Signature. a JWT typically looks like the following.
The first line is header, and the second line is payload, and the last line is signature.
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwIjoxLCJ0IjoxNjQyMTc4ODQ4MDAwLCJiIjoiMzIxNzc2MiIsInciOjEwMDAsImsiOiJ7XCJ1XCI6IFwiNVkxaWlpWDE5bU09XCIsIFwiaVwiOiBcInBmaSt0Yy8wQThUN2JxMWdwSzZQSkE9PVwiLCBcInRcIjogXCJ6V2tSL3U4cnZvWHpieWJjWVkraEtRPT1cIiwgXCJiXCI6IFwiL3F3bys0bVJRV3c9XCIsIFwiblwiOiBcImgrMGI0eTg4K2hJPVwifSIsImlhdCI6IjE2NDIxNzg4NDgifQ.yC7c8yXBg1UuQwYYBJZJi5rmwFtnwZax5FBoo0YnwpM
Parts broken down
Header
Header is typically consists of two part: the type of the token and the signing
algorithm used, such as HMAC, SHA256 and RSA. The field eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
is
base4encoded and the clear text is following.
{"alg": "HS256","typ": "JWT"}
Payload
Payload contains the claims which consists of key infomation. An example payload can be:
{"p": "2","t": 1642172692000,"b": "3217762","w": 1000,"k": "{\"u\":\"xwB6a62fRZc=\",\"i\":\"XG+8ka3tPGSVpzE2IObupQ==\",\"t\":\"P2ODj+rhbTaw8NT/BbUOAQ==\",\"b\":\"oUQ+QqYwe34=\",\"n\":\"LPwOuFmCb3I=\"}","iat": 1642172692}
This part is also base64 encoded to form the second part of the JWT.
Signature
Signature is generated by encoded header, encoded payload and the algorithm specified in the header(In the above header is HMAC-SHA256
),
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)
The secret
field represents the private key to encrypt the payload. The signature is used to verify the message wasn't changed along the way.
Programming tips
In Python, package like PyJWT
and python-jose
can sign and verify the jwt message. For example, PyJWT
usage:
# jwt_data is dict and jwt_key is str.jwt_enc = jwt.encode(jwt_data, jwt_key, algorithm='HS256')print(jwt_enc.decode(encoding='utf-8'))
In front-end, some sites use jwt as a confusion method for copyright protection. You can try to find the constent field jwt secret like jwtSecret
in their
JavaScript.