简体   繁体   中英

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!

You may have solved this, but adding some more info in case anyone bumps into this.

There is nothing wrong with your code - works fine with valid credentials.

There are three conditions that will return AUTHENTICATION_FAILED , they are:

  • Incorrect username
  • Incorrect password
  • Incorrect Zscaler cloud URL

Incorrect username format will return:

{"code":"INVALID_USERNAME_OR_PASSWORD","message":"INVALID_USERNAME_OR_PASSWORD"}

Incorrect API key or timestamp will return:

{"code":"INVALID_API_KEY","message":"INVALID_API_KEY"}

I'd suggest you check out pyZscaler (I am the author), which is a Python SDK for Zscaler APIs that you might find useful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM