How to generate a RS256 signed token I decode with jose.jwt.decode
Asked Answered
N

1

6

I have a function that takes in a token, decodes it, and uses the payload to perform some logic. I would like to generate tokens with claims I manipulate to test that function.

I generated a keypair from https://mkjwk.org/ and use it in the following way:

    from jose import jwt

    claims = {"hello": "world"}
    key = {
        "kty": "RSA",
        "d": "RSjC9hfDtq2G3hQJFBI08hu3CJ6hRRlhs-u9nMFhdSpqhWFPK3LuLVSWPxG9lN7NQ963_7AturR9YoEvjXjCMZFEEqewNQNq31v0zgh9k5XFdz1CiVSLdHo7VQjuJB6imLCF266TUFvZwQ4Gs1uq6I6GCVRoenSe9ZsWleYF--E",
        "e": "AQAB",
        "use": "sig",
        "kid": "1234567890",
        "alg": "RS256",
        "n": "thBvC_I9NciW6XqTxUFMZaVVpvGx6BvLHd3v8Visk_6OoDCVXF_6vNktNi6W7CBkuHBqGyuF0wDFrHcZuZq_kLKI6IRofEzKyUoReOyYRlPt5ar64oDO-4mwH47fb99ILW94_8RpQHy74hCnfv7d888YaCmta9iOBOvggcvxb5s"
    }

    token = jwt.encode(
        {"hello": "world"},
        key,
        algorithm="RS256",
    )

    jwt.decode(token, key, algorithms="RS256") == claims

The above is giving me a jose.exceptions.JWTError: Signature verification failed. error.

Why is this? How can I generate a token I can properly decode with my desired claims?

Niello answered 29/12, 2018 at 22:13 Comment(2)
Have you looked at their documentation (pyjwt.readthedocs.io/en/latest/usage.html), what have you tried?Tahmosh
@SteveByrne that is the pyjwt library, but I am using python-jose. I have tried running the code sample in my post.Niello
N
10

Figured it out!

Using full public/private key strings:

token = jws.sign({"hello": "world"}, rsa_private_key, algorithm="RS256")
assert jwt.decode(token, rsa_public_key, "RS256") == {"hello": "world"}

Or with JWKs:

# signing with RSA private key
private_key = jwk.construct(rsa_private_key, "RS256").to_dict()
token = jws.sign({"hello": "world"}, private_key, algorithm="RS256")

# verifying with the corresponding JWK (for the public view of the key)
rsa_jwk = {"alg": "RS256", "e": "AQAB", "kid": "example.com#1", "kty": "RSA", "n": "lkMfaGdMNONMTbP4YP63sJGOLangx7s9B-eXnWSOv-MsjrdJBRUgZSyoaVXbrxxxxx6i8bIp-T1-U0X5xcfJVci8Dw_fNqKPbMSrFJy92oAqMZ1Cmwr4ENL6VtVQTmUtR5d3GOWfqZXXp-i2UJpsaDr0ZUF7GCqWaAQW4gy_vI2sl9MinIXrAtUnVH9UlyZ3csEdb3cvRyJ920vEZmKpLR54hMeGxa5G3SlrRZwgNNb1vpOwL51JxifWX3rXRndiVhk98henqog4x4lYnhjotvXZQ","use": "sig"}
assert jwt.decode(token, rsa_jwk, "RS256") == {"hello": "world"}
Niello answered 30/12, 2018 at 0:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.