Granting authorization to the API with Python
Heading over to Python, you will now create a program to grant authorization to the API. Begin by running the following command in your command line/terminal to install the required python package.
python -m pip install requests
This command may vary by operating system, you may need to change 'python' to 'python3'. Also, ensure your PATH environment variable is properly set for python.
- Create a new python program under
fetchtoken.py
name. - Import the requests package with the following command.
import requests
- Define the
tokenURL
,clientid
, andclientsecret
variables by running the following.
tokenURL = 'http://your-openiam-instance/idp/oauth2/token'clientid = 'yourclientid'clientsecret = 'yourclientsecret'
- Create a function for obtaining an authentication token by the following program.
def getToken():# Configtoken_url = tokenURLclient_id = clientidclient_secret = clientsecret# Request tokenresponse = requests.post(token_url, data={'grant_type': 'client_credentials'}, auth=(client_id, client_secret))if response.status_code == 200:token_data = response.json()access_token = token_data.get('access_token')if not access_token:print('Error: Access token not found in the response')else:print(f'Error: {response.status_code}, {response.text}')return access_token
- An optional step is printing the authentication token to the terminal for testing by running the following command.
print(getToken())
When you run the file, you should get an auth token printed to your terminal, e.g.
PS C:\Users\maxim\OneDrive\Desktop\openiam\restapi> python fetchtoken.pyINwAgD9qSmS-EOlD-YF9JDUheohKk.cR0WCvW--Y.oxoxgR8SNw6m
The finished program should look as follows.
import requeststokenURL = 'http://192.168.86.28:8080/idp/oauth2/token'clientid = 'D051B01D50B14096AB1F3D91B2ED7EF3'clientsecret ='5a0db7b3f7b8ff31b9a55cf5c16a7afa502d933021d1744b8e3941dea3f56d1a'def getToken():# Configtoken_url = tokenURLclient_id = clientidclient_secret = clientsecret# Request tokenresponse = requests.post(token_url, data={'grant_type': 'client_credentials'}, auth=(client_id, client_secret))if response.status_code == 200:token_data = response.json()access_token = token_data.get('access_token')if not access_token:print('Error: Access token not found in the response')else:print(f'Error: {response.status_code}, {response.text}')return access_token