Zscaler api authenticate using Python

I am trying to authenticate to Zscaler with API. By reading the documentation and following the examples in the following sites

I wrote the following code:

    import time
    import http.client
    import json
    
    
    def obfuscate_api_key():
        seed = 'myActualKey'
        time_now = int(time.time() * 1000)
        n = str(time_now)[-6:]
        r = str(int(n) >> 1).zfill(6)
        obf_key = ""
        for i in range(0, len(str(n)), 1):
            obf_key += seed[int(str(n)[i])]
        for j in range(0, len(str(r)), 1):
            obf_key += seed[int(str(r)[j]) + 2]

        return time_now, obf_key
    
    
    now, key = obfuscate_api_key()
    
    conn = http.client.HTTPSConnection('zsapi.zscalertwo.net')
    
    payload = {"username": "my@username.com", "password":"mypassword", "apiKey": key,
               "timestamp": now}
    
    headers = {
        'content-type': "application/json",
        'cache-control': "no-cache"
    }
    
    conn.request("POST", "/api/v1/authenticatedSession", json.dumps(payload), headers)
    
    res = conn.getresponse()
    data = res.read()
    
    print(data.decode("utf-8"))

However, I keep getting the following message:

{“code”:“AUTHENTICATION_FAILED”,“message”:“AUTHENTICATION_FAILED”}

My credentials are correct because I use them to authenticate in the web GUI. I have the necessary priviledges to use the api since I have an api key. The hostname is also correct, thats what I use to login from the browser. I have also tried with admin.zscalertwo.net but the results are the same.
Any ideas of what could cause this problem will be more than welcome. Thanks!

1 Like

You are missing
import requests

Also see if everything is in line, otherwise script works fine i just tested it.

2 Likes

Thanks Stefan for your quick reply and help.
It seems that there are some local implications that cause that issue that don’t have to do with the code. Hence, we can close this issue.
Thank you.

2 Likes

Quick note in case anyone also copies this code for testing with dummy credentials:

API Keys are exactly 12 alphanumeric characters long, so you must update the seed variable or the obfuscate_api_key() function can throw out of index errors.