from keycloak import KeycloakOpenID
import requests
import jwt
import json
import base64
keycloak_openid = KeycloakOpenID(server_url="http://localhost:8080/auth/",
client_id="your_client_id",
realm_name="your_realm",
client_secret_key="your_client_secret")
auth_url = keycloak_openid.auth_url(
redirect_uri="http://localhost:8000/callback",
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: ")
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):
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))