Skip to content
Snippets Groups Projects

Update auth lib

Merged Aleksandra Wardzinska requested to merge update_auth_lib into master
1 unresolved thread
10 files
+ 31
117
Compare changes
  • Side-by-side
  • Inline
Files
10
import argparse
from pprint import pprint
import jwt
import requests
from authlib.integrations.requests_client import OAuth2Session
import logging
import datetime
DEFAULT_SERVER = "auth.cern.ch"
DEFAULT_REALM = "cern"
DEFAULT_REALM_PREFIX = "auth/realms/{}"
DEFAULT_TOKEN_ENDPOINT = "api-access/token"
TARGET_API = "authorization-service-api"
def get_token_endpoint(server=DEFAULT_SERVER, realm=DEFAULT_REALM):
@@ -19,43 +17,24 @@ def get_token_endpoint(server=DEFAULT_SERVER, realm=DEFAULT_REALM):
server, DEFAULT_REALM_PREFIX.format(realm), DEFAULT_TOKEN_ENDPOINT
)
def get_api_token(
client_id, client_secret, target_application, token_endpoint=get_token_endpoint()
client_id, client_secret, token_endpoint=get_token_endpoint()
):
logging.debug(
"[x] Getting API token as {} for {}".format(client_id, target_application)
)
r = requests.post(
token_endpoint,
auth=(client_id, client_secret),
data={"grant_type": "client_credentials", "audience": target_application},
"[x] Getting API token as {} for {}".format(client_id, TARGET_API)
)
if not r.ok:
logging.error("ERROR getting token: {}".format(r.json()))
exit(1)
client = OAuth2Session(client_id, client_secret)
token = client.fetch_token(token_endpoint, grant_type='client_credentials', audience=TARGET_API)
response_json = r.json()
token = response_json["access_token"]
expires_in_seconds = response_json["expires_in"]
expiration_datetime = datetime.datetime.now() + datetime.timedelta(
seconds=expires_in_seconds
)
logging.debug(jwt.decode(token, verify=False))
logging.debug("[x] Token obtained")
return token, expiration_datetime
return token["access_token"]
parser = argparse.ArgumentParser()
parser.add_argument("client_id", help="Your client ID")
parser.add_argument("client_secret", help="Your client secret")
parser.add_argument(
"target_application", help="The client ID for which you want to exchange the token"
)
parser.add_argument("--client_id", help="Your client ID")
parser.add_argument("--client_secret", help="Your client secret")
parser.add_argument(
"--realm", help="The keycloak realm, default: cern", type=str, default=DEFAULT_REALM
)
@@ -70,12 +49,10 @@ if __name__ == "__main__":
args = parser.parse_args()
token_endpoint = get_token_endpoint(args.server, args.realm)
logging.debug(f"[x] Token endpoint: {token_endpoint}")
api_token, expiration_datetime = get_api_token(
api_token = get_api_token(
args.client_id,
args.client_secret,
args.target_application,
token_endpoint=token_endpoint,
)
print(api_token)
pprint(jwt.decode(api_token, verify=False))
print(f"The token expires: {expiration_datetime}")
\ No newline at end of file
Loading