tim peterson
tim peterson

Reputation: 24305

Python - How To Decode JWT Header?

I have a token that includes the following header eyJraWQiOiI4NkQ4OEtmIiwiYWxnIjoiUlMyNTYifQ.

How can I obtain the following JSON decoding of it as jwt.io provides?

{
  "kid": "86D88Kf",
  "alg": "RS256"
}

jwt.decode() doesn't give this header.

Thanks!

Upvotes: 5

Views: 17215

Answers (2)

jps
jps

Reputation: 22515

In PyJwt use get_unverified_header(token) for that. This is especially useful to obtain the key id (kid) before you verify the token. So in the last line I show how to extract the kid from the header.

import jwt
token = "eyJraWQiOiI4NkQ4OEtmIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"
header = jwt.get_unverified_header(token)
print (header)
print (header['kid'])

Result:

{'kid': '86D88Kf', 'alg': 'RS256'}
86D88Kf

as described in the documentation

Upvotes: 14

tdelaney
tdelaney

Reputation: 77347

This is an unencrpyted header. Its a URL-safe base64 encoding of a JSON encoding of the data you want. You need to add padding characters to the end of the encoded string to make sure its on a 4 character boundary, then decode.

>>> import json
>>> import base64
>>> token = "eyJraWQiOiI4NkQ4OEtmIiwiYWxnIjoiUlMyNTYifQ"
>>> padded = token + "="*divmod(len(token),4)[1]
>>> padded
'eyJraWQiOiI4NkQ4OEtmIiwiYWxnIjoiUlMyNTYifQ=='
>>> jsondata = base64.urlsafe_b64decode(padded)
>>> jsondata
b'{"kid":"86D88Kf","alg":"RS256"}'
>>> data = json.loads(jsondata)
>>> data
{'kid': '86D88Kf', 'alg': 'RS256'}

Upvotes: 14

Related Questions