JWT parsing

임정민·2024년 9월 30일

메모장

목록 보기
5/33
post-thumbnail
import jwt
import base64
import json
from jwt.algorithms import RSAAlgorithm

# Example JWT token
token = "your_access_token_here"

# 1. Split the JWT into its components: header, payload, and signature
header_b64, payload_b64, signature_b64 = token.split('.')

# 2. Decode header and payload (Base64 decoding)
header = base64.urlsafe_b64decode(header_b64 + '==').decode('utf-8')
payload = base64.urlsafe_b64decode(payload_b64 + '==').decode('utf-8')

# 3. Convert header and payload to JSON format
header_json = json.loads(header)
payload_json = json.loads(payload)

print("Header:", header_json)
print("Payload:", payload_json)

# 4. Use the 'kid' (Key ID) from the header to get the correct public key from Keycloak
# You can fetch the public key from Keycloak's JWKS endpoint, or use a predefined public key

# Keycloak's JWKS endpoint: https://<keycloak-domain>/auth/realms/<realm-name>/protocol/openid-connect/certs

# Assuming you've fetched and formatted the public key (in PEM format) from Keycloak
public_key_pem = """-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtd....
-----END PUBLIC KEY-----"""

# 5. Verify the token using the public key and the algorithm from the header
algorithm = header_json['alg']

try:
    decoded = jwt.decode(token, public_key_pem, algorithms=[algorithm])
    print("Decoded JWT:", decoded)
except jwt.ExpiredSignatureError:
    print("The token has expired")
except jwt.InvalidTokenError:
    print("Invalid token")

# Signature is automatically verified during this process, 
# as `jwt.decode()` handles the signature verification using the public key.
import jwt
from jwt import ExpiredSignatureError, InvalidSignatureError, DecodeError, ImmatureSignatureError, InvalidTokenError

try:
    # JWT 디코딩 및 서명 검증
    decoded = jwt.decode(token, public_key_pem, algorithms=["RS256"])
    print("Decoded JWT:", decoded)

except ExpiredSignatureError:
    print("Error: The token has expired. Please request a new one.")

except InvalidSignatureError:
    print("Error: The token's signature is invalid. Check if the correct public key is being used.")

except ImmatureSignatureError:
    print("Error: The token is not yet valid (check 'nbf' claim).")

except DecodeError:
    print("Error: The token could not be decoded. It might be malformed.")

except InvalidTokenError as e:
    print(f"General Invalid Token Error: {e}. The token is invalid for some reason.")
profile
https://github.com/min731

0개의 댓글