LoginSignup
23
17

More than 3 years have passed since last update.

jwtの中身を見る

Last updated at Posted at 2018-01-23

jwtの文字列は https://jwt.io/ から拝借しました。
ライブラリを利用する場合は PyJWT をどうぞ。

※ライブラリを利用しないケースは、署名の検証はしていません。

import base64
import json

jwt_ = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ'

tmp = jwt_.split('.')

header = json.loads(base64.b64decode(tmp[0]).decode())
payload = json.loads(base64.b64decode(tmp[1]).decode())

# >>> header
# {'alg': 'HS256', 'typ': 'JWT'}
# >>> payload
# {'name': 'John Doe', 'admin': True, 'sub': '1234567890'}

以下、PyJWTを利用したケース。
署名はHS256で、シークレット値="secret"です。

# pip install PyJWT

import jwt

jwt.decode(jwt_, verify=False)
# {'sub': '1234567890', 'admin': True, 'name': 'John Doe'}

# PyJWTライブラリのバージョンが新しい(2.0.1で確認)場合、上記はエラーになるので、以下のように書きます。
jwt.decode(jwt_, options={"verify_signature": False})


jwt.decode(jwt_, 'secret', algorithms=['HS256'])
# {'sub': '1234567890', 'admin': True, 'name': 'John Doe'}

jwt.decode(jwt_, 'fuga', algorithms=['HS256'])
# ...
#    raise DecodeError('Signature verification failed')
# jwt.exceptions.DecodeError: Signature verification failed

作成と検証

>>> header
{'alg': 'HS256', 'typ': 'JWT'}
>>> payload
{'sub': '1234567890', 'admin': True, 'name': 'John Doe'}
>>> result = jwt.encode(payload, 'secret', algorithm='HS256', headers=header)
>>> result
b'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwiYWRtaW4iOnRydWUsIm5hbWUiOiJKb2huIERvZSJ9.9IELajTU43KKXdIpYMyiS0ARBsngz3EiLAT-3tZGDLY'
>>> jwt.decode(result, 'secret', algorithms=['HS256'])
{'sub': '1234567890', 'admin': True, 'name': 'John Doe'}
23
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
17