4

我有一个函数,它接收一个令牌,对其进行解码,并使用有效负载来执行一些逻辑。我想使用我操纵的声明生成令牌以测试该功能。

我从https://mkjwk.org/生成了一个密钥对,并以下列方式使用它:

    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

以上是给我一个jose.exceptions.JWTError: Signature verification failed.错误。

为什么是这样?我怎样才能生成一个可以用我想要的声明正确解码的令牌?

4

1 回答 1

6

弄清楚了!

使用完整的公钥/私钥字符串:

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

或使用 JWK:

private_key = jwk.construct(rsa_private_key, "RS256").to_dict()
public_key = jwk.construct(rsa_public_key, "RS256").to_dict()

token = jws.sign({"hello": "world"}, private_key, algorithm="RS256")
assert jwt.decode(token, public_key, "RS256") == {"hello": "world"}
于 2018-12-30T00:11:51.043 回答