Skip to content

Accessing Secured REST API Endpoints from Jupyter Notebook

Ramesh Maddegoda edited this page Jun 1, 2022 · 4 revisions

A JupyterHub was setup on AWS as explained in https://github.com/unity-sds/unity-cs/wiki/Amazon-Cognito-Authentication-with-JupyterHub.

The same JupyterHub was used to login (with Cognito) and open a Jupyter Notebook.

Getting an access token from a Jupyter Notebook

After opening the Jupiter Notebook, a JWT token can be obtained by using an approach documented in https://github.com/unity-sds/unity-cs/wiki/Getting-Cognito-JWT-Tokens-in-Command-Line as follows (the following steps show Approach 3).

  1. Create a JSON file called auth.json as follows with,

    • The username and password of the user
    • The ClientId of the related App Client configured

    Replace <COGNITO_CLIENT_ID>, <USER_NAME> and the <USER_PASSWORD> with the correct values. The relevant COGNITO_CLIENT_ID can be obtained from the Unity CS team.

auth.json

{
   "AuthParameters" : {
      "USERNAME" : "<USER_NAME>",
      "PASSWORD" : "<USER_PASSWORD>"
   },
   "AuthFlow" : "USER_PASSWORD_AUTH",
   "ClientId" : "<COGNITO_CLIENT_ID>"
}

  1. Upload the above auth.json to Jupyter Notebook.

  2. Execute the following python code to get the token (make sure to use the correct AWS Region instead of the <AWS_REGION> below).

import requests
import json

url     = 'https://cognito-idp.<AWS_REGION>.amazonaws.com'

# Read auth.json file
auth_file = open("auth.json")
payload = json.load(auth_file)

# Set headers
headers = {
    'X-Amz-Target': 'AWSCognitoIdentityProviderService.InitiateAuth',
    'Content-Type': 'application/x-amz-json-1.1'
}

# POST request
res = requests.post(url, json=payload, headers=headers)

# Print access token
access_token = res.json()['AuthenticationResult']['AccessToken']

Accessing a secured REST API from Jupyter Notebook

The access_token obtained in above section can be passed as the Authorization header to access a secured REST API as follows. The following example has URL specific to WPS-T endpoints. You may change this URL to match with your setup.

  1. In the same Jupyter Notebook (which was used to get the access_token above), add the following code.
    import requests
    import json

    url     = 'https://<API_GATEWAY_BASE_URL>/dev/ades_wpst/processes'


    # Set headers
    headers = {
        'Authorization': 'Bearer ' + access_token
    }


    # GET request (use requests.post for POST requests)
    response = requests.get(url, headers=headers)

    # Print the response
    print(response.json())

  1. Execute the above code in Jupyter Notebook to see the results.