Keycloak JWT Decoding

임정민·2024년 9월 27일

메모장

목록 보기
4/34
post-thumbnail
from keycloak import KeycloakOpenID
import requests
import jwt
import json
import base64

# Keycloak 설정
keycloak_openid = KeycloakOpenID(server_url="http://localhost:8080/auth/",
                                 client_id="your_client_id",
                                 realm_name="your_realm",
                                 client_secret_key="your_client_secret")

# Authorization Code 요청 URL 생성
auth_url = keycloak_openid.auth_url(
    redirect_uri="http://localhost:8000/callback",  # 가상의 콜백 URL
    scope="openid email profile"
)

print(f"Please visit this URL to authorize: {auth_url}")
print("After authorization, you will be redirected. Copy the 'code' parameter from the URL.")

# 사용자로부터 인증 코드 입력 받기
code = input("Enter the 'code' parameter from the redirected URL: ")

# Authorization Code를 이용해 토큰 요청
token = keycloak_openid.token(
    grant_type='authorization_code',
    code=code,
    redirect_uri="http://localhost:8000/callback"
)

# 액세스 토큰 추출
access_token = token['access_token']

print("\nAccess Token:")
print(access_token)

# 토큰 디코딩 함수
def decode_token(token):
    # Keycloak의 공개키 가져오기
    keys = keycloak_openid.certs()
    public_key = keys['keys'][0]['x5c'][0]
    public_key = f"-----BEGIN CERTIFICATE-----\n{public_key}\n-----END CERTIFICATE-----"

    # 토큰 디코딩
    options = {
        'verify_signature': True,
        'verify_exp': True,
        'verify_nbf': True,
        'verify_iat': True,
        'verify_aud': True
    }

    try:
        decoded = jwt.decode(
            token,
            public_key,
            algorithms=['RS256'],
            audience=keycloak_openid.client_id,
            options=options
        )
        return decoded
    except jwt.ExpiredSignatureError:
        return 'Token has expired'
    except jwt.InvalidTokenError:
        return 'Invalid token'

# 토큰 디코딩
decoded_token = decode_token(access_token)

print("\nDecoded Token:")
print(json.dumps(decoded_token, indent=2))

# 사용자 정보 가져오기
userinfo = keycloak_openid.userinfo(access_token)

print("\nUser Info:")
print(json.dumps(userinfo, indent=2))
profile
https://github.com/min731

0개의 댓글