I am trying to make a POST request to URL , to authenticate myself ( can't share the URL as it is for work). The authentication worked and I got the token access. However , I need to extract the token access header to use it in other function , I don't want to copy the token and paste it .
So , I tried to do this :
response = requests.post(url, data = dic,json={'key':'value'}) # dic is my username and password
token =response.request.headers['AccessToken']
But it is still running , I did not get an error or any output ( I am using Jupyter Notebook)
response = requests.post(url, data = dic) # this one works fine but it does not meet the requirement
Additional clarification :
I am asking the user for (username and password) , then I place them into dic which I pass into the POST request.
Example of Server Response :
{"Result":{"AccessToken":"#####="},"Success":true,"Message":"","ErrorCode":""}
Is there other way to access the AccessToken header of the server response ?
Any ideas?
Thank you
You need to check that there is a header containing an access token in your response.headers dict. You'll probably want to look for an Authorization header, which you'll need to extract the actual token from. In the cases that I'm aware of, that header contents will be
"Authorization": "Bearer encoded-access-token-goes-here"
so you'd check
if "Authorization" in response.headers:
token = response.headers["Authorization"].split()[1]
Example of Server Response :
{"Result":{"AccessToken":"#####="},"Success":true,"Message":"","ErrorCode":""}
Since that is a response, and not a header, you want something like
token = None
try:
token = response.json()["Result"]["AccessToken"]
except KeyError:
print("No token found")
print(response.text)
Related
I'm trying to replicate a login to a page with python and the requests module but I need a token bearer.
This site doesn't require a login password connection but just an event code (wooclap.com)
I cannot find when the token is recovered by looking at header and json responses.
If you can help me
Thanks
once you put in a event code check the network tab on you're chrome console there should be a request wich returns the token. either in the reponse header or the json,
I'd recommend finding it using DevTools in your browser (F12).
In network you can see the login request mainly under headers and response. I've used this to implemented it below in python for you.
import requests
# Set the URL of the login page
url = "https://app.wooclap.com/api/auth/local/login"
# Set the login credentials
data = {"username": "< !!enter username here!! >", "password": "< !!enter password here!! >"}
# Send the login request and store the response
response = requests.post(url, data=data)
# Get the JSON response body
json_response = response.json()
# Get the AWT token from the JSON response
awt_token = json_response.get("token")
# Set the URL of the resource you want to access
url = "https://app.wooclap.com/public/events"
# Set the authorization header of your request, using the Bearer scheme
headers = {"Authorization": f"Bearer {awt_token}"}
# Send the request and store the response
response = requests.get(url, headers=headers)
print(response.text)
To send a GET request with a Bearer Token authorization header using Python, you need to make an HTTP GET request and provide your Bearer Token with the Authorization: Bearer {token} HTTP header
I'm having problems on taking the access token from the oauth2 platform with python.
Currently, that's what I'm using on my post request:
def token(self):
client_id=ID_DO_CLIENTE
client_secret=SECRET_TOKEN
grant_type='client_credentials'
response = requests.post("https://oauth2.googleapis.com/token",
auth=(client_id, client_secret),
data={'grant_type':grant_type,'client_id':client_id,'client_secret':client_secret})
print(response.text)
This specific code is returning the following error:
{
"error": "unsupported_grant_type",
"error_description": "Invalid grant_type: "
}
But I don't think the problem is the grant_type, since I've tried everything I've found online to solve this.
Anyway, if there's any info missing, please let me know. Please help !
A valid request will also need these headers in order to send data in the correct format - I suspect JSON is sent by default, resulting in a malformed request:
Content-Type: application/x-www-form-url-encoded
Authorization: Basic [base 64 encoded client id and secret]
TECHNIQUES
Aim to use the curl tool to get the token first, to ensure the setup is right - as in this article.
Also aim to trace the request via an HTTP proxy tool to ensure that the wire message is being sent correctly.
These techniques will make you more productive when working with OAuth.
CODE
I had a search and this answer seems to use the correct code, though you may be able to send the Authorization header like this:
auth=HTTPBasicAuth('user', 'pass')
This is a sample code for reference:
data = {'grant_type': 'client_credentials'}
requests.post(token_url,
data=data,
auth=(client_id, client_secret))
In the provided sample code, the data part is being sent incorrectly viz:
data={'grant_type':grant_type,'client_id':client_id,'client_secret':client_secret}
I think it should be this:
data={'grant_type':grant_type}
Adding the sample code which I am testing to verify the token generation logic:
client_id = '<value>'
client_secret = '<value>'
# This is optional
scope = '<uri>'
#Token generation step
#If scope is not defined above then remove it from this call
data = {'grant_type': 'client_credentials','scope': scope}
access_token_response = requests.post(token_url, data=data, verify=False, allow_redirects=False, auth=(client_id, client_secret))
print (access_token_response.headers)
print (access_token_response.text)
tokens = json.loads(access_token_response.text)
print ("access token: " + tokens['access_token'])
I am trying to make a post request within the Matchbook API.
I have logged in and I got below "Session- Tocken":
{"session-token":"xxxx_b0b8a6f22a82396b6afcfa344f3022","user-id":xx685,"role":"USER"}
However, I am not sure how to make the post request. See below code used:
headers = {"session-token" : "xxxx_b0b8a6f22a82396b6afcfa344f3022"}
r = requests.post('https://api.matchbook.com/edge/rest/reports/v1/offers/current/?odds-type=DECIMAL&exchange-type=binary¤cy=EUR, headers = headers')
print r.text
Below is the error message that I got. It does not make sense to me because I logged in successfully and got the above session-token in response.
{"errors":[{"messages":["You are not authorised to access this resource. Login to continue."]}]}
Am I properly indicating the session-token in the header information of the post request?
You need to pass headers argument in post function.
headers = {"session-token" : "xxxx_b0b8a6f22a82396b6afcfa344f3022"}
response = requests.post('https://api.matchbook.com/edge/rest/reports/v1/offers/current/?odds-type=DECIMAL&exchange-type=binary¤cy=EUR', headers=headers)
also if you need to get an json response, just call json() function on response variable.
something like response.json()
I am trying to create RFC in cherwell using REST API in Python. I tried first in Swegger UI. I got it working there. I am able to create RFC successfully. Then by following that Curl Request, in python, using request module, I tried and got 401. I found it why i am getting 401. It's because of in Authorization i am using Bearer which is a temporary token. It will live only for 10 minutes. If i do request after 10 minutes i got a 401. Bearer is a compulsory field. I can't make a request without it. I tried to pass username and password instead of Bearer, it didn't work. below is my request,
with open('C:\Cherwell\payload.json') as file:
Data = json.load(file)
payload = Data
header = {"Authorization":"Bearer XXXXXXXX"}
r = requests.post("https:/URL/CherwellAPI/api/V1/savebusinessobject?
api_key=XXXX-XXXX-XXXX-XXXX", auth=('user','pass'), headers = header,
data=json.dumps(payload))
print r
It will be great, if anyone can help who have done this before! Please Advice
Appreciate any help!
Found this solution that I used to address a similar problem. It's a function that requests a token from /CherwellAPI/token and returns a properly formatted Bearer token. You need to pass this Bearer token along in API requests as a Authorization parameter in the API header. Should look like token=bearer_token.
import json
import requests
configFile = 'config.json'
with open(configFile) as cf:
config_data = json.load(cf)
def getCherwellToken():
params = {'apikey' : config_data['cherwell']['client_id']}
data = {'grant_type' : 'password',
'client_id' : config_data['cherwell']['client_id'],
'username' : config_data['cherwell']['username'],
'password' : config_data['cherwell']['password']}
url = 'https://.cherwellondemand.com/CherwellAPI/token'
session = requests.post(url=url, data=data)
if session:
token = json.loads(session.text)
else:
token = None
return 'Bearer ' + token['access_token']
using another call Get Token You can get access token and using that you can request to create a new ticket. This worked for me.
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 :-)