[英]How do I decode a JWT token in Python
我大致在關注這個SO questions和 this article 。 每個用例與我的用例略有不同。
我正在嘗試,只給定令牌和 url,解碼從 Auth0 收到的 JTW 令牌;
def get_key():
KEY_URL = r"https://dev-dluzlcxa.us.auth0.com/pem"
filename = wget.download(KEY_URL)
public_key = open(filename, 'r').read()
key = public_key.encode()
return key
token = get_token()
key = get_key()
jwt.decode(token, key=key, algorithms=['RS256', ])
出於安全原因,我沒有在此處提供令牌(或 get_token())方法,但我已使用 jwt.io 驗證我確實擁有一個有效令牌。 我嘗試了各種排列組合,但似乎沒有任何效果。
我最近的錯誤,在很多錯誤中,是這樣的;
ValueError: ('Could not deserialize key data. The data may be in an incorrect format, it may be encrypted with an unsupported algorithm, or it may be an unsupported key type (e.g. EC curves with explicit parameters).', [_OpenSSLErrorWithText(code=151584876, lib=9, reason=108, reason_text=b'error:0909006C:PEM routines:get_name:no start line')])
我能夠找到解決方案(注意,這是使用 Auth0 作為提供者。)
import jwt
import http.client
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.backends import default_backend
from jwt import PyJWKClient
import pprint
AUTH_ENDPOINT=<your auth endpoint>
AUDIENCE = <your app>
CLIENT_ID = <your client id>
CLIENT_SECRET = <your client secret>
PUBLIC_KEY_URL = fr"https://{AUTH_ENDPOINT}/.well-known/jwks.json"
def get_token():
conn = http.client.HTTPSConnection(AUTH_ENDPOINT)
payload = dict(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
audience=AUDIENCE,
grant_type=r"client_credentials"
)
headers = { 'content-type': "application/json" }
conn.request("POST", "/oauth/token", json.dumps(payload), headers)
res = conn.getresponse()
data = res.read()
message = json.loads(data.decode("utf-8"))
token = message['access_token']
return token;
def decode(token: str):
jwks_client = PyJWKClient(PUBLIC_KEY_URL)
signing_key = jwks_client.get_signing_key_from_jwt(token)
data = jwt.decode(
token,
signing_key.key,
algorithms=["RS256"],
audience=AUDIENCE,
options={"verify_exp": False},)
return data
token = get_token()
data=decode(token)
pprint.pprint(data)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.