Failed to decode basic authentication token Python 3.10 - python

I am creating script to send calls to API endpoints via simple python functions. I have the following function to retrieve my OAuth2 token (I will remove the URLs and credentials and nevermind the padding)
def get_new_token():
auth_server_url = "my auth url here"
client_id = "my client id here"
client_secret = "my secret here"
auth_headers = {'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'}
token_req_payload = {'grant_type': 'client_credentials'}
token_response = requests.post(auth_server_url,
data=token_req_payload, verify=False, allow_redirects=False,
auth=(client_id, client_secret), headers=auth_headers)
I am then successfully retrieving token with the following line:
return token_response.json()["access_token"]
Then, I can successfully make a request to one of the endpoints, here is my function (also, nevermind the padding):
def call_api_v1_accounts(token):
api_call_headers = {
'Content-Length': '10204',
'Content-Type': 'application/json',
'User-Agent': 'removed',
'Authorization': 'Bearer ' + token}
data = {"here": "is my payload"}
api_call_response = requests.post(my_url, headers=api_call_headers, data=json.dumps(data), verify=False)
print(api_call_response.text)
This request go through fine and I retrieve the information I need, here is the sample of response (I also removed actual data due to security reasons)
{"timestamp":"2022-08-09T10:24:29.713Z","account":{"id":"omitted"},"web":{"href":"omitted"},"sdk":{"token":"omitted"},"workflowExecution":{"id":"omitted","credentials":[{"id":"omitted","category":"ID","omitted":["WEB","API","SDK"],"api":{"token":"ommitted]}]}}
Here is my problem, finally. I have another function which uses the same token, function is below (nevermind the padding)
def call_api_netverify_acquisitions(token):
api_call_headers = {
'Content-Length': '10204',
'Content-Type': 'application/json',
'User-Agent': 'removed',
'Authorization': 'Basic ' + token}
data = {'mydata':'ishere'}
api_call_response = requests.post(my_url, headers=api_call_headers, data=json.dumps(data), verify=True)
print(api_call_response.text)
And the response I receive with it is the following:
{"message":"Failed to decode basic authentication token.","httpStatus":401,"requestUri":"endpoint_url_here"}
I really have no idea what's wrong with that? I printed the len(token) and it returned 867 so I decided I need to add one more symbol to that (so it can be divided by 4), I've added "=" or "===" or "=======" and the result is the same. I understand that one function uses 'Bearer' and other one uses 'Basic', but I still have no idea what to look for.
I am really struggling, please help.

Related

How to refetch the access token in a Python script automatically after it expires?

so I am working on fetching data from an api using access token only. I have created two python scripts, one for fetching the token and the other for fetching data. I have created a common variable 'token' for both scripts. However when token expires in 15 minutes, I have to restart the script manually. Is there an solution for this problem?
Auth Code:
response = requests.request("POST", url, headers=headers, data=payload)
token = response.json()['access_token']
Fetch Sample:
response2 = requests.request("GET", qurl, headers=headers2, data=payload2)
r2=response2.json()
payload={}
headers = {
'Host': 'proxy.sample.com',
'Accept': 'application/vnd.sample.v1+json',
'Authorization': 'Basic
MFQxOE5HYmFsUURGYzBnWkh6b3ZwZVJkN0a1Y3BMQ3w6dnwnamFZa3Ric2p4OUFPUg==',
'Accept-Encoding': 'br;q=1.0, gzip;q=0.9, deflate;q=0.8',
'Accept-Language': 'en-US;q=1.0, ar-US;q=0.9',
'Content-Type': 'application/json',
'User-Agent': 'SampleApp/3.37.0 (com.sample.mobile.consumer; build:3.#; iOS
14.4.1) Alamofire/5.2.2',
'access_token': token
Note: I don't want more than one instance of the script at once.
Just a thought, assuming you're using a loop you could use except.
Therefore when the error procs the code will log you back in and continue
e.g.
while True:
try:
{script here}
except {ErrorType}:
print('token expired')
{relogin code}
continue

REST API post request results in successful request but not creation

I've been trying to make a Post Request to my CRM API. The CRM API is very vague:
"You can use POST request when you wish to create records. You POST a JSON encoded string to the servers and it will return a single instance of the record."
POST /{object_name}
Example:
Request URL (POST):
/accounts
Request Body (JSON):
{
"name": "testing API"
}
I've had plenty of success making GET requests regularly, but POST is not working out so easily.
url = "https://apiv4.reallysimplesystems.com/accounts?<KEY>"
payload = {"name":"Ziggy","owner":"XYZ","addresscounty/state":"Awe","source":"Space"}
headers = {
'Content-Type': 'application/json',
'Cookie': 'XSRF-TOKEN=<TOK>; really_simple_systems_session=<KEY>'
}
response = requests.post(url, headers=headers, data=payload)
I get a status code 200 when I run this, but I'm really looking for that 201. The only clue that I've got to follow at this point is that when I run:
response.json()
I get the error:
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I've tried switching the response parameters to json:
response = requests.post(url, headers=headers, json=payload)
I've tried ensuring that my payload is json by using json.dumps():
payload = {"name":"Ziggy","owner":"XYZ","addresscounty/state":"Awe","source":"Space"}
payload = json.dumps(payload)
And I've tried all sorts of other shenanigans that I can't even recall at this point. Does anyone have any idea where I'm going wrong here? The 200 status code makes me feel painfully close.
Replace <AUTH_TOKEN> with your auth token
url = "https://apiv4.reallysimplesystems.com/accounts/"
payload = {"name":"Ziggy"}
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer <AUTH_TOKEN>',
}
response = requests.post(url, headers=headers, data=payload)
Problem solved:
import json
import requests
url = "https://apiv4.reallysimplesystems.com/accounts"
payload = {"name":"RSS Test Joe Bloggs","addresscounty/state":"Maryland","source":"Word of Mouth"}
payload = json.dumps(payload)
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer <AUTH KEY>'
}
response = requests.post(url, headers=headers, data=payload)
Rather than using Postman's code which included the in the URL and used :
'Cookie': 'XSRF-TOKEN=<TOK>; really_simple_systems_session=<KEY>'
I replaced it with a standard Authorization header. Secondly, I found that using json.dumps(payload) and json = payload was resulting in a Bad Request.

How to generate json response from python?

I am making an API call from Python. My current code is supposed to generate a JSON response, but throws out a Response code 500 (Internal Server Error). However, when I generate the data using the API's built in extract tool, it returns the data. Code snippet is as follows:
def Performance(data):
BASEURL = 'https://api-c31.ict.com/inContactAPI/'
accessToken = (data["access_token"])
#Check if accessToken is empty or null
if accessToken!= "":
#Give necessary parameters for http request
payload={'startDate':'1/1/2020',
'endDate':'1/6/2020',
'fields':'"agentId","teamId","totalHandled"'}
#add all necessary headers
header_param = { 'User-Agent' : 'Chrome/79.0.3945.117',
'Authorization': 'bearer ' + '{accessToken}',
'content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json, text/javascript, */*'
}
# Make get http request
response_1 = requests.get(BASEURL + 'services/{version}/agents/performance' , headers = header_param, params=payload)
#answer1.raise_for_status
#print response appropriately
print (response_1)
#response
else: print('error')
response_1 generates a Response 500. How can I generate the data from Python?
params doesn't encode your payload as JSON; json does.
response_1 = requests.get(
BASEURL + 'services/{version}/agents/performance',
headers=header_param,
json=payload)

python how do i put a variable in command string

I'm new to python and cannot figure out how to do the following.
I want to put a variable inside a command but its not working. The command is taking the variable name not its value.
The script below calls https with username and password to get a token. I token is returned . I then need to use the token to create a user.
I'm having issues with it, "token" in the iplanet pair is not getting expanded correctly. It is set correctly as I can print it out before the command. So token would contain something like "AQIC5wM2LY4Sfcydd5smOKSGJT" , but when the 2nd http call is made it gets passed the word token , rather than tokens value.
import requests
import json
url = "https://www.redacted.com:443/json/authenticate"
headers = {
'X-Username': "user",
'X-Password': "password",
'Cache-Control': "no-cache",
}
response = requests.request("POST", url, headers=headers)
tokencreate = json.loads(response.text)
token=tokencreate['tokenId']
print token
url = "https://www.redacted.com:443/json/users"
querystring = {"_action":"create"}
payload = "{\r\n\"username\":\"Patrick\",\r\n\"userpassword\":\"{{userpassword}}\",\r\n\"mail\":\"patrick#example.com\"\r\n}"
headers = {
'iPlanetDirectoryPro': "token",
'Content-Type': "application/json",
'Cache-Control': "no-cache",
}
response = requests.request("POST", url, data=payload, headers=headers, params=querystring)
print(response.text)
It's because you are passing the string 'token' when you mean to pass the variable token
here you create the token:
tokencreate = json.loads(response.text)
token=tokencreate['tokenId']
print token
But you don't use the actual variable, it should look like this:
payload = "{\r\n\"username\":\"Patrick\",\r\n\"userpassword\":\"{{userpassword}}\",\r\n\"mail\":\"patrick#example.com\"\r\n}"
headers = {
'iPlanetDirectoryPro': token,
'Content-Type': "application/json",
'Cache-Control': "no-cache",
}

How to make Raw REST Call for Azure using Python

I am trying to make REST Call for azure using python,
Have created Access token using ADAL in python.
But getting Error called "provided Authorization header is in invalid format."
Here is the code for that:
import adal
import requests
token_response = adal.acquire_token_with_username_password(
'https://login.windows.net/abcd.onmicrosoft.com',
'user-name',
'password'
)
access_token = token_response.get('accessToken')
url = 'https://management.azure.com/subscriptions/{subscription- id}/providers/Microsoft.Network/virtualnetworks?api-version=2015-06-15'
headers = {'Content-Type': 'application/json',
'Authorization': access_token}
response = requests.get(url=url,headers = headers)
print(response.status_code)
print(response.text)
Can anyone tell me how the access-token should look like?
And is this the correct way to generate token for REST in python?
I am reffering this link for above code:
https://msdn.microsoft.com/en-us/library/azure/mt163557.aspx
As #GauravMantri said, the format of the value of the header Authorization is Bearer <access-token> that you can refer to the section Calling ARM REST APIs of the doc "Resource Manager REST APIs".
For example in the section above.
GET /subscriptions/SUBSCRIPTION_ID/resourcegroups?api-version=2015-01-01 HTTP/1.1
Host: management.azure.com
Authorization: Bearer YOUR_ACCESS_TOKEN
Content-Type: application/json
You would need to prepend Bearer to your token. Something like:
headers = {'Content-Type': 'application/json',
'Authorization': 'Bearer ' + access_token}

Categories

Resources