Skip to content

Examples

SSO examples

User Info endpoint

This example script obtains a Keycloak access token using client credentials and calls the /userinfo endpoint:

Note: In case the client access type is public the client_secret can be empty.

import requests
import sys
import json
import base64
from getpass import getpass

kc_server= "https://auth.cern.ch"

# You can use this "public-client" test client,
# or replace the client (application) ID and secret
# with the ID and secret of your application.
client_id = "public-client"
client_secret = ""

keycloak_endpoint = kc_server+"/auth/realms/cern/protocol/openid-connect/token"
userinfo_endpoint = kc_server+"/auth/realms/cern/protocol/openid-connect/userinfo"

username = input("Username: ")
password = getpass("Password: ")
totp = input("TOTP code (if you don't have 2FA enabled, just press Enter): ")

print("\n### Response ####################################################\n")
token_resp = requests.post(
    keycloak_endpoint,
    data={
        "grant_type": "password",
        "scope": "openid",
        "client_id": client_id,
        "client_secret": client_secret,
        "password": password,
        "username": username,
        "totp": totp
    }
).json()
print(json.dumps(token_resp, indent=4))

if "error" in token_resp.keys():
    sys.exit(1)

print("\n### Access Token ####################################################\n")
access_token = token_resp['access_token']
print(access_token)

print("\n### Access Token payload ############################################\n")
# take the payload from the JWT token
payload = json.loads(base64.b64decode(access_token.split(".")[1] + '=='))
print(json.dumps(payload, indent=4))

print("\n### ID Token ########################################################\n")
id_token = token_resp['id_token']
print(id_token)

print("\n### ID Token payload ################################################\n")
# take the payload from the JWT token
payload = json.loads(base64.b64decode(id_token.split(".")[1] + '=='))
print(json.dumps(payload, indent=4))

print("\n### User Info #######################################################\n")
userinfo = requests.post(
    userinfo_endpoint,
    data={"access_token": access_token}
).json()
print(json.dumps(userinfo, indent=4))