Exchange Access Token As An Application¶
This notebook is intended for development and testing purpose only. It shall allow you to exchange an access token for an application using its dedicated client id and client secret.
The use case is an application that needs to access the API on behalf of a user later in time, but the user is not present to authorize the application. Typically, the ADES stages out the processing results after a long running job. In that case the initial access token may be expired by the time the ADES needs to push the results. Thus, the ADES must exchange the access token of the user a priori and refresh it when needed.
In this notebook, we will:
- exchange an access token for an application
- refresh the access token
from IPython.display import JSON
from authlib.jose import jwt
import requests
from authlib.oidc.discovery import well_known, OpenIDProviderMetadata
t2_oidc_dicovery_url = well_known.get_well_known_url('http://iam.terradue.com/auth/realms/master', external=True)
t2_oidc_dicovery = OpenIDProviderMetadata(requests.get(t2_oidc_dicovery_url).json())
# HERE set yourt client id and secret
client_id = 'ellip-test-ades'
client_secret = input('client secret: ')
# please adjust the scopes to the platform you are accessing (e.g. gep, ellip, etc.)
scope = 'openid email profile offline_access ellip gep'
# Create the client
from authlib.integrations.requests_client import OAuth2Session
client = OAuth2Session(client_id, client_secret=client_secret, scope=scope, code_challenge_method='S256')
# Ask for user initial access token
user_access_token = input('user access token: ')
# Exchange the token for an offline one
token = client.fetch_token(t2_oidc_dicovery.token_endpoint,
grant_type= 'urn:ietf:params:oauth:grant-type:token-exchange',
subject_token=user_access_token,
subject_token_type='urn:ietf:params:oauth:token-type:access_token',
audience='ellip-test-ades')
# Print the token
JSON(token)
Now you have an ACCESS TOKEN that we will use to make requests to the API. The access token is actually a JWT token that contains the user's information. The token is signed by the server and can be verified by the server. The token is also encrypted so that the user's information is not visible to anyone else. Let's consult the claims of the token
public_key = requests.get(t2_oidc_dicovery['jwks_uri']).json()['keys'][0]
claims = jwt.decode(token['access_token'], public_key)
JSON(claims)
Refreshing the Access Token¶
The access token is valid for a limited time. When it expires, you need to refresh it. The refresh token is valid for a longer period of time. You can use the refresh token to get a new access token.
# Refresh the token
token = client.refresh_token(t2_oidc_dicovery.token_endpoint, refresh_token=token['refresh_token'])
# Print the token
JSON(token)