概要
pythonでjwtを検証してみる。
参考にしたページ
サンプルコード
# coding: utf-8
# Your code here!
import base64
import json
import jwt
jwt_ = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ'
tmp = jwt_.split('.')
header = json.loads(base64.b64decode(tmp[0]).decode())
payload = json.loads(base64.b64decode(tmp[1]).decode())
print(header)
print(payload)
print(jwt.decode(jwt_, options = {"verify_signature": False}))
print(jwt.decode(jwt_, 'secret', algorithms = ['HS256']))
result = jwt.encode(payload, 'secret', algorithm = 'HS256', headers = header)
print(result)
print(jwt.decode(result, 'secret', algorithms = ['HS256']))
header = "{\"alg\":\"HS256\",\"typ\":\"JWT\"}"
payload = "{\"sub\":\"1234567890\",\"iat\":1516239022}"
header = json.loads(header)
payload = json.loads(payload)
print(header)
print(payload)
result = jwt.encode(payload, 'secretkey', algorithm = 'HS256', headers = header)
print(result)
print(jwt.decode(result, 'secretkey', algorithms = ['HS256']))
実行結果
{'alg': 'HS256', 'typ': 'JWT'}
{'sub': '1234567890', 'name': 'John Doe', 'admin': True}
{'sub': '1234567890', 'name': 'John Doe', 'admin': True}
{'sub': '1234567890', 'name': 'John Doe', 'admin': True}
b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.pcHcZspUvuiqIPVB_i_qmcvCJv63KLUgIAKIlXI1gY8'
{'sub': '1234567890', 'name': 'John Doe', 'admin': True}
{'alg': 'HS256', 'typ': 'JWT'}
{'sub': '1234567890', 'iat': 1516239022}
b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwiaWF0IjoxNTE2MjM5MDIyfQ.fta4kBfweubZrnpiTZhk-sjj2DarBLTV0WoZ8Qer9dg'
{'sub': '1234567890', 'iat': 1516239022}
成果物
以上。