API: Python requests 'GET' call returning a 401
Symptom
When programming in Python to use the REST API, a 'POST' method to login will return the required authentication token but a subsequent 'GET' method (for example, to get a list of safes) will fail with a 401 (unauthorized) error.
Environment
11.7;12.0;12.1;12.2;12.6;13.0;13.2;13.1 Privileged Access Manager (PAM, self-hosted) Cyber-Ark API/SDK
Cyber-Ark API/SDK REST API with Python
Cause
The subsequent call that invokes the 'GET' method does not contain the required cookies.
Resolution
First, when using Python to implement the Idira REST API, it is recommended to use the Python requests module. More information can be obtained at https://docs.python-requests.org/en/latest/
Make sure that the requests and json modules are both imported.
The requests module not only contains the necessary methods to perform HTTP methods but also contains the methods to obtain the necessary authentication cookie which is required in subsequent calls during the same session. The cookie can be returned as a Python dictionary type which can be inserted into the 'GET' method for a successful call to the API.
1. Use the request 'POST' to login via the API and get the authentication token
response = requests.post(url=s_url,data=j_header,verify=False) # s_url is the logon URL and j_header is the logon information in JSON format
2. Format the authentication token: '{"Authorization":"<string of returned token>"}'.
Header is {'Authorization': 'NTMxODEzYmQtZmM4Ni00OGFhLTk5ZGItY2E2ZGZkZjU3ODI5OzIwNDZEODBBREY2RkE3MUY4MTE1OTQ5NkZDMzlENTgzOUFERUI0MTQ1OTIxNEI3MzM4QzBFRjQ4NjBBRjE4QzM7MDAwMDAwMDIzOTdBREVEM0VGRUVCMDQ2MTc0NTBDQTQ4NUNEMzNBRkFBRUMyRkEzOUMwRkY0OTg5RUU3MEU2MUU5RjUzQ0NBMDAwMDAwMDA7', 'Content-Type': 'applcation/json'}
The token can be obtained with response.json()
# Example
response = requests.post(url=s_url,data=j_header,verify=False)
s_Token = response.json()
s_authHdr = '{\"Authorization\":\"' + s_Token + '\"}'
j_authHdr = json.dumps(s_authHdr) # Convert the auth header to JSON
Now, use a GET to call the API.
d_Cookie = response.cookies.get_dict() # This is the list of cookies returned from login
response = requests.get(url=s_url,params=j_authHdr,cookies=d_Cookie,verify=False)
The API should return a code of 200, assuming that the token and cookies are correct