Examples
SSO examples
-
Examples of SSO-protected applications (Electron, GoLand, JS, Java Spring, native mobile app etc.) are available at https://gitlab.cern.ch/authzsvc/docs/keycloak-sso-examples
-
An example of an SSO-protected API: https://gitlab.cern.ch/authzsvc/docs/motd-api-example
-
An example on how to set up an Apache proxy with Single Sign-On for any web application, using Puppet module it-puppet-module-cernsso_apache
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
theclient_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))