如何使用pyJWT验证此JWT上的签名?

时间:2018-12-19 22:27:33

标签: python jwt pyjwt

我已收到JWT令牌。 我有兴趣拆包并验证其内容。

我想使用pyJWT库来做到这一点。请参阅下面的小程序。

我已成功将base64解码为JWT。而且我已经从网上检索到匹配的JWK。但是我不知道下一步该怎么做才能验证签名。

当我尝试执行下面的jwt.decode()时,出现错误jwt.exceptions.DecodeError: Not enough segments

# !/usr/bin/env python

import jwt
import base64
import json
import requests

my_jwt = "eyJqa3UiOiJodHRwczovL2U5N2I4YTlkNjcyZTRjZTQ4NDVlYzY5NDdjZDY2ZW" \
         "Y2LXNiLmJhYXMubmludGVuZG8uY29tLzEuMC4wL2NlcnRpZmljYXRlcyIsImtp" \
         "ZCI6ImZlOWRiYmZmLTQ3MGItNDZjOC04YmFmLTFiNzY5OGRlZTViZSIsImFsZy" \
         "I6IlJTMjU2In0.eyJpc3MiOiJodHRwczovL2U5N2I4YTlkNjcyZTRjZTQ4NDVl" \
         "YzY5NDdjZDY2ZWY2LXNiLmJhYXMubmludGVuZG8uY29tIiwiZXhwIjoxNTQ1MT" \
         "g1NDk2LCJ0eXAiOiJpZF90b2tlbiIsImF1ZCI6IjhkOTc1NTllNjNlY2NkNTYi" \
         "LCJiczpkaWQiOiI2NjJhZTQwOWYwNTQyYTBjIiwic3ViIjoiOTNkYmYwNDdiYT" \
         "I3NzQ5NSIsImp0aSI6IjY1NDg4ZjJmLTI1NzAtNDBkYy04ODQ3LTMzODNlZWIx" \
         "MGJiYiIsIm5pbnRlbmRvIjp7ImFpIjoiMDEwMGY4MDAwMDQ5MjAwMCIsImF2Ij" \
         "oiMDAwMCIsImVkaSI6ImJjNTdiYmM3MTZlMDA1MGFmOWRhN2NkYTIzMWRjZDgy" \
         "IiwiYXQiOjE1NDUxNzQ2OTZ9LCJpYXQiOjE1NDUxNzQ2OTZ9.ZMUIt3wYrbfhX" \
         "nnDh4WraGlKrZy0YuL5prluY70sU_-0W5XvWIB-xmTrLz7LJWHEGwTskcWf81_" \
         "HBq_mSb75rMfTAEBwBmOJ4ITmhdnXksz8w7EDOWuPPSEft5XLMNOMD16ztEOYe" \
         "5ddU_iqNEbT56L7fcAJEXv0FWy6H_OutxOglYpDaNkcj6CWJ7dpA0JbqerR9dE" \
         "szaLwyn1ZBDPVD0YeAIm5bEr61imeedzMb0amxlTl4R87mqK6epsFUnRy6p6Kl" \
         "r27_DlTLQ-gej09W7NeNzONCj4thHgCr9szAiaN28krfTc2fobz3qFCoC_eQgh" \
         "iIIZBe_-Lksng3Eg6tw"

decoded_token = [
    base64.b64decode(i + '=' * (-len(i) % 4))
    for i in my_jwt.split('.')
]
header = json.loads(decoded_token[0])
claims = json.loads(decoded_token[1])
signature = decoded_token[2]

print 'Header = \n{}\n\n'.format(header)
print 'Claims = \n{}\n\n'.format(claims)
print 'Signature = \n{}\n\n'.format(signature)

key_found = False
for curr_jwk in requests.get(header['jku']).json()['keys']:
    if curr_jwk['kid'] == header['kid']:
        key_found = True
        break
assert key_found
print 'curr_jwk = {}\n\n'.format(curr_jwk)

# I am not sure if the following line is correct
jwt.decode(signature, curr_jwk['x5c'][0], algorithms=['RS256'])

下面是完整的输出。请告诉我如何验证签名。我在网上找不到适合我的python示例。

Header =
{u'jku': u'https://e97b8a9d672e4ce4845ec6947cd66ef6-sb.baas.nintendo.com/1.0.0/certificates', u'alg': u'RS256', u'kid': u'fe9dbbff-470b-46c8-8baf-1b7698dee5be'}


Claims =
{u'aud': u'8d97559e63eccd56', u'iss': u'https://e97b8a9d672e4ce4845ec6947cd66ef6-sb.baas.nintendo.com', u'jti': u'65488f2f-2570-40dc-8847-3383eeb10bbb', u'exp': 1545185496, u'nintendo': {u'ai': u'0100f80000492000', u'edi': u'bc57bbc716e0050af9da7cda231dcd82', u'at': 1545174696, u'av': u'0000'}, u'iat': 1545174696, u'bs:did': u'662ae409f0542a0c', u'typ': u'id_token', u'sub': u'93dbf047ba277495'}


Signature =
�dr>�X�ݤn��G�D�6��)�d�T=x&�+�X�y�s1��S��|�j���lI�˪z*Z��9S�OV�׍��B��a������v�J�M͟���P�m>z/� �d�����H:�)


curr_jwk = {
    u'use': u'sig', 
    u'e': u'AQAB', 
    u'kty': u'RSA', 
    u'alg': u'RS256', 
    u'n': u'twZRFUFinbzSF9aCaLqSdDSfS4Lfz6bSB-4ymwqkgJPLMLtX0meEVOSsx2qP_OQFkb6_RAZk3GK2CSM46V8A-bZqYn1jHyRyQeQmAfrzvXxAiXBdSq4Eso1C_roFQDjR3p-RnLWDLdMPUHkmAQSPEpVAUbcCvUD8zZwQ-go8GAzG0iQNNvZxma1JQoDsHPgY5LiBVBlqY43tp_jeW_sb3SxZ30zzIckKtQfYDfph_vns-q1_raNRPgS0TQw4E470n27UgLE30yoVn_DlYwmtZneCOWIByVPrMBMIkrv_Gh9VW3GszbqZz2u3K9Aj7rtnCtmUrI9dQbeTnruWOn_Fjw', 
    u'x5c': [u'MIIC/zCCAeegAwIBAgIHBX0u6g3YCzANBgkqhkiG9w0BAQUFADBAMT4wPAYDVQQDEzVlOTdiOGE5ZDY3MmU0Y2U0ODQ1ZWM2OTQ3Y2Q2NmVmNi1zYi5iYWFzLm5pbnRlbmRvLmNvbTAeFw0xNzEyMTYwMDAwMDBaFw0xOTEyMTcwMDAwMDBaMEAxPjA8BgNVBAMTNWU5N2I4YTlkNjcyZTRjZTQ4NDVlYzY5NDdjZDY2ZWY2LXNiLmJhYXMubmludGVuZG8uY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtwZRFUFinbzSF9aCaLqSdDSfS4Lfz6bSB+4ymwqkgJPLMLtX0meEVOSsx2qP/OQFkb6/RAZk3GK2CSM46V8A+bZqYn1jHyRyQeQmAfrzvXxAiXBdSq4Eso1C/roFQDjR3p+RnLWDLdMPUHkmAQSPEpVAUbcCvUD8zZwQ+go8GAzG0iQNNvZxma1JQoDsHPgY5LiBVBlqY43tp/jeW/sb3SxZ30zzIckKtQfYDfph/vns+q1/raNRPgS0TQw4E470n27UgLE30yoVn/DlYwmtZneCOWIByVPrMBMIkrv/Gh9VW3GszbqZz2u3K9Aj7rtnCtmUrI9dQbeTnruWOn/FjwIDAQABMA0GCSqGSIb3DQEBBQUAA4IBAQBsXUY5j/m4pAB0R3zDEHHBXZUCkdN53zCr5M7/Kn4ak0vKb9Hk1gNJqdS+dNyW1C7aNGFPmmcMhOos3tv0KsjNoftA4A27uIA7U6QYtJSUVbtVJgYCu8XUa2VDongGNxB72UvFiD++qY3Xe95b0kzsoSOqGaguicAeRSG/HARDaNJT5I9MhCYdCmjU/z83dGI0t8v33Zua92YVmzL6E06lxQ7KrVa9MlKgVJEiAnju3GESVFmrhEoVt516EVxvTVmFlrsvN6rh+c/jC3mBDkE7E23ukg6FpM8oCVRU/5o8/lnKVcRhYPnBgHwg/wTL/Is5rteMtLihV/mvgt3InWkc'],
    u'usage': u'developer', 
    u'kid': u'fe9dbbff-470b-46c8-8baf-1b7698dee5be'
}

Traceback (most recent call last):
  File "./saqib_test.py", line 46, in <module>
    jwt.decode(signature, curr_jwk['x5c'][0], algorithms=['RS256'])
  File "/Users/saqib.ali/saqib-env-987/lib/python2.7/site-packages/jwt/api_jwt.py", line 84, in decode
    payload, _, _, _ = self._load(jwt)
  File "/Users/saqib.ali/saqib-env-987/lib/python2.7/site-packages/jwt/api_jws.py", line 183, in _load
    raise DecodeError('Not enough segments')
jwt.exceptions.DecodeError: Not enough segments

2 个答案:

答案 0 :(得分:1)

首先,您应该直接解码base64编码的消息。那是一条完整的jwt消息,而不仅仅是签名。应该是:

jwt.decode(my_jwt, algorithms='RS256')

第二,它不起作用,因为默认情况下不支持RS256。您可以参考以下问题:https://github.com/jpadilla/pyjwt/issues/181

最后,我认为您不能在没有公钥的情况下解码此RS256编码的消息。你有钥匙吗?

答案 1 :(得分:1)

您的解码过程非常困难。

这是一个可解码JWT令牌的衬里:

JWT_SECRET = 'secretpassphrase'
JWT_ALGORITHM = 'HS256'
decoded = json.loads(json.dumps(jwt.decode(token, JWT_SECRET, JWT_ALGORITHM)))

此行的作用是使用用于生成令牌的秘密密码对令牌进行解码,然后,“ json.dumps”将其加载为字节格式,下一个“ json.loads”允许您使用以下代码对其进行解析。

之后,您将能够获得令牌的各个属性,如下所示:

user_id = decoded['user_id']
expiry_time = decoded['exp']

注意:这应该放在Try:Catch语句中,因为如果令牌已过期或不使用相同的签名,则python将抛出错误。 无效的签名或令牌已过期。

def verify_token(token):
    try:
        decoded = json.loads(json.dumps(jwt.decode(token, JWT_SECRET, JWT_ALGORITHM)))
        return {
           'name': decoded['user_id'],
           'exp': decoded['exp']
           }
    except:
        print("Generic Error")

希望这会有所帮助