PyJWT raises Signature verification failed

sungyong picture sungyong · Sep 4, 2018 · Viewed 9.1k times · Source

I'm trying to verify JWT which issued by ThingsBoard. But verification was failed with Signature verification failed

My test code is at below.

def test_jwt_decoding():
    jwt_options = {
        'verify_signature': True,
        'verify_exp': True,
        'verify_nbf': False,
        'verify_iat': True,
        'verify_aud': False
    }
    token = 'eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbkB0LW1vbmV0LmNvbSIsInNjb3BlcyI6WyJURU5BTlRfQURNSU4iXSwidXNlcklkIjoiODNiYmEzNDAtMDI3ZC0xMWU4LWI4ZmEtYWY1YjU0OTEyMDA0IiwiZmlyc3ROYW1lIjoi7ISx64Ko7IucIiwibGFzdE5hbWUiOiLqtIDrpqzsnpAiLCJlbmFibGVkIjp0cnVlLCJpc1B1YmxpYyI6ZmFsc2UsInRlbmFudElkIjoiMzkwMTNjNzAtMDI3ZC0xMWU4LWI4ZmEtYWY1YjU0OTEyMDA0IiwiY3VzdG9tZXJJZCI6IjEzODE0MDAwLTFkZDItMTFiMi04MDgwLTgwODA4MDgwODA4MCIsImlzcyI6InRoaW5nc2JvYXJkLmlvIiwiaWF0IjoxNTM1OTU1NDE2LCJleHAiOjM2NzU5NTU0MTZ9.N1Ms0LA7WtOel1pg6lTMRNDJosY3qfR6Q4SVuAUwmDPmTj4uYnKU0B-9Wdlqmg4HQRUXa23edOTU-TnAxfBoyg'
    try:
        jwt.decode(
            token,
            'thingsboardDefaultSigningKey',
            algorithms=['HS512'],
            options=jwt_options
        )
        assert True
    except Exception as err:
        print(str(err))
        assert False

I checked the signature was verified at jwt.io Only difference was secret base64 encoded on at jwt.io

enter image description here

I'm gussing secret base64 encoded made this differences.
What should I do for that?

Answer

Steve Boyd picture Steve Boyd · Sep 4, 2018

jwt.decode(..) expects the key value to be the actual secret in a text string, no encoding. It appears that your token was encoded with a routine that expected the secret was base64 encoded. It was just lucky that your secret, 'thingsboardDefaultSigningKey' happens to decode properly as base64.

Change your call to:

jwt.decode(
    token,
    b64decode('thingsboardDefaultSigningKey'),
    algorithms=['HS512'],
    options=jwt_options
)

It will then decode without the exception.