Skip to content

Instantly share code, notes, and snippets.

@sphr2k
Last active July 1, 2023 17:59
Show Gist options
  • Save sphr2k/0596f40af7a943773c5246768efb226d to your computer and use it in GitHub Desktop.
Save sphr2k/0596f40af7a943773c5246768efb226d to your computer and use it in GitHub Desktop.
OIDC Example
#! /usr/bin/env python3
from keycloak import KeycloakOpenID
from dotenv import dotenv_values
import json
from rich.console import Console
from rich.panel import Panel
from rich.syntax import Syntax
## Load config from .env
config = dotenv_values(".env")
## Functions
def print_json_box(title, content):
console = Console()
# Format JSON
formatted_content = json.dumps(content, indent=2)
# Syntax highlight JSON
highlighted_content = Syntax(formatted_content, "json", theme="solarized-dark", background_color="default", word_wrap=True)
# Create the panel
panel = Panel.fit(
highlighted_content,
title=title,
title_align="left",
border_style="bright_blue",
padding=(1, 2),
width=80,
)
# Print the panel
console.print(panel)
## Main code
# Create an instance of KeycloakOpenID with the necessary configuration
keycloak_openid = KeycloakOpenID(
server_url=config['KEYCLOAK_SERVER_URL'],
realm_name=config['KEYCLOAK_REALM'],
client_id=config['CLIENT_ID'],
client_secret_key=config['CLIENT_SECRET']
)
# Authenticate client using client credentials flow
token = keycloak_openid.token(grant_type='client_credentials')
print_json_box("Full token", token)
# Decode access_token
KEYCLOAK_PUBLIC_KEY = "-----BEGIN PUBLIC KEY-----\n" + keycloak_openid.public_key() + "\n-----END PUBLIC KEY-----"
options = {"verify_signature": True, "verify_aud": False, "verify_exp": True}
access_token = keycloak_openid.decode_token(token['access_token'], key=KEYCLOAK_PUBLIC_KEY, options=options)
print_json_box("Access token", access_token)
# Introspect access_token (requires client ID and secret - would of course use API's credentials, not the client's)
introspect = keycloak_openid.introspect(token['access_token'])
print_json_box("Introspected access token", introspect)⏎
python-keycloak==3.0.0
python-dotenv==1.0.0
rich==13.4.1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment