authorization token changing repeatedly - python

I wrote a python script which sends POST requests to some particular website. In order to perform this request, I need the authorization token which keeps changing. my current solution is to use Chrome Dev tools (Network tab) to obtain the new token. I was wondering if there is any way to obtain the new token automatically, or any other way to get around this problem.
this is my current code:(Note that in the provided code general text has been replaced with "...")
import requests
import json
url = "..."
payload = {...}
headers = {...,
"Authorization": "Bearer ...",
...}
response = requests.post(url, data=json.dumps(payload), headers=headers)

Related

Get Request to Azure DevOps with Personal Access Token (PAT) using Python

I'm trying to make a get request to Azure DevOps.
I have the URL and the Personal_Access_Token. The URL was created following these intructions https://learn.microsoft.com/en-us/rest/api/azure/devops/git/items/get?view=azure-devops-rest-6.1&tabs=HTTP#definitions , and it is working fine in the browser. It is possible to see the information of the file that I'm targeting.
However, when I execute the request in python:
import requests
headers = {
'Authorization': 'Bearer myPAT',
}
response = requests.get('exampleurl.com/content', headers=headers)
I'm getting the 203 response...
I have also try other options following this link Python requests library how to pass Authorization header with single token without success. Including these headers:
personal_access_token_encoded = base64.b64encode(personal_access_token.encode('utf-8')).decode('utf-8')
headers={'Authorization': 'Basic '+personal_access_token_encoded}
headers={'Authorization': 'Basic '+personal_access_token}
But in both cases still having the same response.
For sure I'm not considering something. What could be missing?
For Azure DevOps API, you need to use Basic Auth instead of Baerear, providing only the PAT token encoded in base64.
Hi error feedback 203 is about your invalid token.
So what is the authorization type of your request call?
For pat headers = {'Authorization': 'Basic pat'}
For bearer token headers = {'Authorization': 'Bearer MYREALLYLONGTOKENIGOT'}
You could put your rest api in postman and click the code button at the right-side bar to overview the rest api into different script.

Wix API linking error with https, code not working

When I try to link the Wix API, I get this error:
The redirect url doesn’t match the one defined in your app configuration. Double check that it starts with https.
I looked at the code and it already has https:
import requests
def handler(pd: "pipedream"):
token = f'{pd.inputs["wix"]["$auth"]["oauth_access_token"]}'
authorization = f'Bearer {token}'
headers = {"Authorization": authorization, "Content-Type": 'application/json'}
r = requests.get('https://www.wixapis.com/contacts/v4/contacts', headers=headers)
# Export the data for use in future steps
return r.json()
What should I do here?
api linking not working

Python API request to internal API with OKTA Authentication

I used to selenium for downloading special reports from webpage where I have to login. Webpage has integrated OKTA Authentication plugin . I find out that there would be better and more effective use internal API requests. So I tried find how to use request python library with creating session, but I am unsuccessful. I tried this code, but it ends with 400 error.
payload = {"password":"password","username":"username","options":{"warnBeforePasswordExpired": True,"multiOptionalFactorEnroll": True}}
with requests.Session() as s:
p = s.post('https://sso.johndeere.com/api/v1/authn', data=payload)
r = s.get("requested_url")
print(p)
I am unable get throw auth. Has anybody experience with breaking OKTA auth plugin using requests library?
Thanks
Best Regards
Merry Christmas and Welcome to Stackoverflow!
Firstly, an HTTP error code of 400 error means one or more settings is wrong at the client side. You can learn more about it here.
You seem to be missing out important headers configuration. You need to set the content-type header correctly otherwise the destination server won't be able to process your data.
Also, as a bonus point. You need to format your payload into a valid JSON string before sending out the request too.
import requests
import json
# Setup proper headers
headers = {
"accept": "application/json, text/plain, */*",
"content-type": "application/json; charset=UTF-8"
}
# Your body data here
payload = {"password":"password","username":"username","options":{"warnBeforePasswordExpired": True,"multiOptionalFactorEnroll": True}}
payload_json = json.dumps(payload) # Format it into a valid JSON str
with requests.Session() as s:
p = s.post('https://sso.johndeere.com/api/v1/authn', headers=headers, data=payload_json)
r = s.get("requested_url")
print(p.content)

Genius API Search result successful but no hits

When making a call to the Genius API (the music lyric service) search capability to search for a specific song by title, my GET request is successfully processed and returns a HTTP status code of 200, but the JSON response returns no hits for the song I searched.
{u'meta': {u'status': 200}, u'response': {u'hits': []}}
Notice the value for the hits key is an empty array. This is strange, since when "testing" the same call on the Genius API Docs site https://docs.genius.com/#web_pages-h2 with the same OAuth2 access token I'm able to get 10 hits for the same search. I've tried searching multiple song titles with the same results.
I'm using Python 2.7.12, and I replaced my API call access token with AccessTOKEN below so I'm not sharing that publicly (though I was testing with the correct access token)
#!/usr/bin/env python
# -*- coding=utf-8 -*-
import requests
baseUrl = "http://api.genius.com"
headers = {'Authorization': 'Bearer AccessTOKEN'}
searchUrl = baseUrl + "/search"
songTitle = "Shelter"
data = {'q': songTitle}
response = requests.get(searchUrl, data=data, headers=headers)
json = response.json()
print json
Any ideas?
The data parameter is used for a POST request. Since this is a GET request, you should pass your data to the params parameter.
response = requests.get(searchUrl, params=data, headers=headers)

HP QC REST API using python

I tried to connect HP QC using python to create defects and attach files, but I am not able to connect with HP QC. Here is my code:
domain='DEFAULT_773497139'
project='773497139_DEMO'
import requests
url = "https://almalm1250saastrial.saas.hpe.com/qcbin/"
querystring = {"username":"user#gmail.com","password":"password"}
headers = {
'cache-control': "no-cache",
'token': "5d33d0b7-1d04-4989-3349-3005b847ab7f"
}
response = requests.request("POST", url, headers=headers, params=querystring)
#~ print(response.text)
print response.headers
new_header = response.headers
new_url = url+ u'rest/domains/'+domain+u'/projects/'+project
new_querystring = {
"username":"user#gmail.com",
"password":"password",
"domain":'DEFAULT_773497139',
"project":'773497139_DEMO'
}
print new_url
response = requests.request("POST", new_url, headers=new_header, params=new_querystring)
print(response.text)
Now login works fine, but when try other API it asks for, I would get this message:
Authentication failed. Browser based integrations - to login append '?login-form-required=y' to the url you tried to access
If the parameter has been added, then it goes back to login page.
Seems that your urls are not well builded:
base_url ='https://server.saas.hpe.com/qcbin/'
base_url + '/qcbin/rest/domains/
you will get:
..../qcbin/qcbin/...
qcbin twice
The way I do it is to based on python request Sessions. First I create a session, then post my credentials to ../authentication-point/alm-authenticate/ (or sth like this, you should check it) and then using this session I can get, post or do whatever I want.
So:
s = requests.Session()
s.post(`../authentication-point/alm-authenticate/`, data=credentials)
# now session object is authenticated and recognized
# you can s.post, s.get or whatever
I think it's a good url, but I can't check it right now :)
Session issue has beensolved by LWSSO cookie (LWSSO_COOKIE_KEY).
Just send a unicode string to your server and use the header for the basic Authorization as specified by the HP REST API:
login_url = u'https://almalm1250saastrial.saas.hpe.com/qcbin/authentication-point/authenticate'
username,password = user,passwd
logs = base64.b64encode("{0}:{1}".format(username, password))
header['Authorization'] = "Basic {}".format(logs)
POST by using the requests module in python is quite easy:
requests.post(login_url, headers=header)
That's it...now you are authenticated and you can proceed with next action :-) To check on that you can "GET" on:
login_auth = u'https://almalm1250saastrial.saas.hpe.com/qcbin/rest/is-authenticated
you should get a code 200 --> That means you are authenticated.
Hope this help you. Have a nice day and let me know if something is still not clear.
p.s.: to send REST msg in python I am using requests module. It is really easy! You can create a session if you want to send multiple actions--> then work with that sessions--> ALM = requests.session(), then use ALM.post(whatever) and so on :-)

Categories

Resources