Skip to content

Authorization Service API Examples

The following are simple python examples of how to call the API. This is a non-exhaustive list. All endpoints can be found on the Authorization Service API Swagger Interface

Applications can be added to groups through the Application Portal on the Group Memberships Tab, or via a SNOW ticket.

group-membership

Get an API token using Client Credentials

import requests
import json
keycloak_api_token_endpoint = "https://keycloak-dev.cern.ch/auth/realms/cern/api-access/token"

token_resp = requests.post(
    keycloak_api_token_endpoint,
    data={
        "grant_type": "client_credentials",
        "client_id": "MY_CLIENT",
        "client_secret": "MY_SECRET",
        "audience" : "authorization-service-api"
    },
    headers={"Content-Type": "application/x-www-form-urlencoded"},
)

api_token = token_resp.json()['access_token']

Get an API token as the user on the command line

import requests

PROD_TOKEN_ENDPOINT = "https://auth.cern.ch/auth/realms/cern/protocol/openid-connect/token"
PROD_DEVICE_ENDPOINT = "https://auth.cern.ch/auth/realms/cern/protocol/openid-connect/auth/device"
PROD_AUTHZSVC_ENDPOINT = "https://authorization-service-api.web.cern.ch/api/v1.0/"
CLIENT_ID = "public-client"

def get_auth_token(token_endpoint, device_endpoint, api_endpoint):
    try:
        device = requests.post(device_endpoint, data={"client_id": CLIENT_ID, "scope": "openid profile"}).json()
        print(f"Go to {device['verification_uri_complete']}")
        input("Press Enter when authenticated...")

        token = requests.post(token_endpoint, data={
            "grant_type": "urn:ietf:params:oauth:grant-type:device_code",
            "device_code": device['device_code'],
            "client_id": CLIENT_ID
        }).json().get("access_token")

        if not token: return None

        api_token = requests.post(token_endpoint, data={
            "grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
            "client_id": CLIENT_ID,
            "subject_token": token,
            "audience": "authorization-service-api"
        }, headers={"Content-Type": "application/x-www-form-urlencoded"}).json().get("access_token")

        print(f"API Token acquired for {api_endpoint}" if api_token else "Token exchange failed.")
        return api_token

    except Exception as e:
        print(f"Error: {e}")

def main():
    token = get_auth_token(PROD_TOKEN_ENDPOINT, PROD_DEVICE_ENDPOINT, PROD_AUTHZSVC_ENDPOINT)
    if token:
        print(f"\nYour API Token:\n{token}")

if __name__ == "__main__":
    main()

Get the Identity object of the caller

authzsvc_endpoint = "https://authorization-service-api-dev.web.cern.ch/api/v1.0/"

me = requests.get(
    "{}Identity/current".format(authzsvc_endpoint),
    headers={"Authorization": "Bearer {}".format(api_token)},
)

my_id = me.json()["data"]["id"]

Update an application

Pre-requisites: The client used to request the token must

  • Be a member of the administrator group for the application
  • Be a member of authorization-service-applications-users
authzsvc_endpoint = "https://authorization-service-api-dev.web.cern.ch/api/v1.0/"
application_id = "08d9421f-1b3f-4785-8889-5034fa343418"

new_role = requests.post(
    "{0}Application/{1}/roles".format(authzsvc_endpoint, application_id),
    headers={"Authorization": "Bearer {}".format(api_token)},
    json={
      "name": f"testrole",
      "displayName": f"test role",
      "description": "testing role creation",
      "required": False,
      "multifactor": False,
      "applyToAllUsers": False,
      "minimumLoaId" : "f0000000-0000-0000-0000-0000000000b4",
      "applicationId": application_id
    }
)

Get group memberships

Pre-requisites: The client used to request the token must

  • Be a member of the administrator group of the group to be queried

OR

  • Be a member of authorization-service-groups-readers
authzsvc_endpoint = "https://authorization-service-api-dev.web.cern.ch/api/v1.0/"
my_group = "testgroup"

my_group_member_identities = requests.get(
    "{0}Group/{1}/members/identities".format(authzsvc_endpoint, my_group),
    headers={
    "Authorization": "Bearer {}".format(api_token),
    }
)

my_group_member_groups = requests.get(
    "{0}Group/{1}/members/groups".format(authzsvc_endpoint, my_group),
    headers={
    "Authorization": "Bearer {}".format(api_token),
    }
)

Add external members to a group

Pre-requisites: The client used to request the token must

  • Be a member of the administrator group of the group to be updated
email="test77@example.com"
authzsvc_endpoint = "https://authorization-service-api-dev.web.cern.ch/api/v1.0/"
my_group = "testgroup"

my_group_new_member = requests.post(
    "{0}Group/{1}/members/identities".format(authzsvc_endpoint, my_group),
    headers={
    "Authorization": "Bearer {}".format(api_token),
    },
    json=[{
        "id": email
    }]
)

Get user information

Note: This endpoint may be used as an alternative to the legacy endpoint http://winservices-soap.web.cern.ch/winservices-soap/TSCSE/Authentication.asmx/GetUserLongInfo

Pre-requisites: The client used to request the token must

  • Be a member of authorization-service-identity-readers
identity = "mcurie"
authzsvc_endpoint = "https://authorization-service-api-dev.web.cern.ch/api/v1.0/"

identities = requests.get(
    "{0}Identity/{1}".format(authzsvc_endpoint, identity),
    headers={"Authorization": "Bearer {}".format(api_token)},
    verify=False
)

You will get a response containing a data object as follows:

{
   "externalEmail":"None",
   "primaryAccountEmail":"None",
   "type":"Person",
   "upn":"mcurie",
   "displayName":"Marie Curie",
   "personId":"77777",
   "supervisorId":"1111-1111-1111-1111-1111",
   "source":"cern",
   "unconfirmed":false,
   "unconfirmedEmail":"None",
   "primaryAccountId":"1111-1111-1111-1111-1111",
   "uid":82828,
   "gid":2727,
   "resourceCategory":"Personal",
   "reassignable":false,
   "autoReassign":false,
   "pendingAction":false,
   "blocked":false,
   "securityIssues":false,
   "blockingReason":"None",
   "blockingTime":"None",
   "blockingDeadline":"None",
   "expirationDeadline":"None",
   "ownerId":"None",
   "id":"1111-1111-1111-1111-1111",
   "room":"111",
   "floor":"1",
   "orcid":"0000-0003-2187-0980",
   "building":"11",
   "lastName":"Curie",
   "cernGroup":"XX",
   "firstName":"Marie",
   "telephone1":"66666",
   "cernSection":"XXX",
   "description":"CERN - XX/XX",
   "instituteName":"CERN",
   "portablePhone":"111111",
   "cernDepartment":"XX",
   "instituteAbbreviation":"CERN",
   "preferredCernLanguage":"EN"
}