I've been trying to post a payload to an endpoint, the endpoint requires bearer token.
using the python requests, I'm trying to post the bearer token in the header as
from requests import Session
http= Session()
accessToken = getToken(url=uri,data=payload)
authorization_header_string = 'bearer ' + accessToken
requestHeaders = {"Content-type": "text/plain", "Authorization":authorization_header_string}
headerData={"content-type":"text/plain","authorization":requestHeaders}
resp= http.post(url=uri,data=payload,headers=headerData)
but all I get is 401 error, while if I use the same token in postman it works fine.
I'm using requestbin to check wherein the authorization shows up only sometimes in the header.
Try the following:
token = "your token"
headerData={"content-type": "text/plain", "authorization": "Bearer " + token}
Related
How to pass bearer token in API call using python request module? Below I have tried:
import requests
import json
api_url = " "# url
todo = "" #Data to send
headers = {"Content-Type":"application/json"} # how to pass bearer token
response = requests.post(api_url, data=json.dumps(todo), headers=headers)
print(response.json())
Define token before and change headers to:
headers = {"Content-Type":"application/json", "Authorization": f"Bearer {token}"}
Below bash script works and returns a token.
curl -X POST --user <id>:<key> 'https://<name>.auth.eu-west-1.amazoncognito.com/oauth2/token?grant_type=client_credentials' -H 'Content-Type: application/x-www-form-urlencoded'
I would now like to generate a token via a Python script. I currently struggle with using requests library, but without success. Below generates Response 400 (bad request).
import requests
parameters = {"user":"<id>:<key>", "Content-Type": "application/x-www-form-urlencoded"}
response = requests.get("https://<name>.auth.eu-west-1.amazoncognito.com/oauth2/token?grant_type=client_credentials", params=parameters)
print(response)
To fix your usage of requests:
Use post() instead of get().
Use an auth object to construct a basic auth header. (Or send credentials in the body)
Remove the content type header; requests will set this for you.
Take the grant_type out of the query string. This belongs in the request body.
While the documentation for the /oauth2/token endpoint says you need to send a basic auth header for client_credentials grant, it also works if you send the client id and secret in the request body (with no auth header).
As such, these python examples both work, and are essentially equivalent:
Credentials in request body:
import requests
url = 'https://<COGNITO_DOMAIN>.auth.<REGION>.amazoncognito.com/oauth2/token'
params = {
"client_secret": "1ixxxxxxxxxxxxxxxxc2b",
"grant_type": "client_credentials",
"client_id": "7xxxxxxxxxxxxxxxt"
}
response = requests.post(url, data=params)
print(response)
print(response.text)
Credentials in basic auth header:
import requests
url = 'https://<COGNITO_DOMAIN>.auth.<REGION>.amazoncognito.com/oauth2/token'
params = {
"grant_type": "client_credentials"
}
auth = ('7xxxxxxxxxxt', '1ixxxxxxxxxxxxxxxc2b')
r = requests.post(url, data=params, auth=auth)
print(r)
print(r.text)
I'm having a problem sending an authorization token with Bearer to an API via python requests.post:
token = "eyJhbGciOiJSUzI1NiIsImtpZCI6IjZjNGE5NDBjNWE5ODE5MGJlNzIwYjI0ZDY2MTMzZWVmIiwidHlwIjoiSldUIn0.eyJuYmYiOjE1NzY4MjU0NzgsImV4cCI6MTU3NjgyOTA3OCwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo0MDQwIiwiYXVkIjpbImh0dHA6Ly9sb2NhbGhvc3Q6NDA0MC9yZXNvdXJjZXMiLCJwYXJjZWxfc3RvcmFnZSJdLCJjbGllbnRfaWQiOiJwcy5tLmNsaWVudCIsInN1YiI6ImI0ZjVmNmVjLWEyMDItNDhjZC1hZmVjLTA4ZDc3OGJmNzYzNyIsImF1dGhfdGltZSI6MTU3NjgyNTQ3OCwiaWRwIjoibG9jYWwiLCJ1c2VybmFtZSI6InZlc3RhIiwic2NvcGUiOlsib3BlbmlkIiwicHJvZmlsZSIsInBhcmNlbF9zdG9yYWdlIiwib2ZmbGluZV9hY2Nlc3MiXSwiYW1yIjpbInB3ZCJdfQ.araPfT_HS0iMXUWS0KcSq3fvowJpu9ONtNsENUtZuk7lV3vxSpyNhUULdZSFdQdZs5830afxRC9qapzYNzDI48ALDrlconKDwReaG9QQhJ61p9dTbSskJDTReGDYwRxEgmZBhjOFD_KeVklbKWevXTGQ2dW3nzGtJ26uMFrSpOww4yNBvJ9Daafson-tZNXeG6xZ09H5GHY43Qp9P25kNRBfeFyKzYuF7xoygk_TQSlMike2Fzjec9TBbudSsTP62qIAXkYckvGF5fI5buJWsw5tvrDtgKVSfVs_SD27-3MIjde27fG89sH-CUYryroy6YiHyTx6UOYTvC2dBNzm5A"
test_url = 'https://fpt.titec.ir/api/v1/parcel/getprecode'
header = {
"Authorization": "Bearer {}".format(token),
"Content-Type": "application/json",
}
data = {'serviceTypeId': '2'}
response = requests.post(test_url, data=data, headers=header)
But every time the response returned 401 status code.
In postman it works well but in python code it doesn't work. Is it a bug in requests.post?
By the way the token expires in 60 min.
Is there anyone who could help me please?
I can do this successfully with requests.get for another url that needs exactly the same token!!
I have tried access the data using post man with bearer token and access key please see screenshot. now i wanted to know How to add accesskey in header on a request in pyhon i have already added the bearer token.
code
headers = {"Authorization": "Bearer sdfjkdsjfs088gftdd'
test = requests.get('http://blah.blah/api/1.0/blah', headers=headers)
You can add additional items to the header by just adding additional key-value pairs to your headers dictionary:
headers = {
"Authorization": "Bearer sdfjkdsjfs088gftdd",
"accesskey": accesskey, # provided accesskey is defined somewhere
}
and then you can make the same request as before:
test = requests.get(url='http://blah.blah/api/1.0/blah', headers=headers)
I'm at the first stage of integrating our web app with PayPal's express checkout api. For me to place a purchase, I have to get a Bearer token of course using our client id and our client secret.
I use the following curl command to successfully get that token:
curl https://api.sandbox.paypal.com/v1/oauth2/token \
-H "Accept: application/json" \
-H "Accept-Language: en_US" \
-u "ourID:ourSecret" \
-d "grant_type=client_credentials"
Now I am trying to achieve the same results in python using urllib2. I've arrived at the following code, which produces a 401 HTTP Unauthorized exception.
import urllib
import urllib2
url = "https://api.sandbox.paypal.com/v1/oauth2/token"
PAYPAL_CLIENT_ID = "ourID"
PAYPAL_CLIENT_SECRET = "ourSecret"
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, PAYPAL_CLIENT_ID, PAYPAL_CLIENT_SECRET)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)
req = urllib2.Request( url=url,
headers={
"Accept": "application/json",
"Accept-Language": "en_US",
},
data =urllib.urlencode({
"grant_type":"client_credentials",
}),)
result = urllib2.urlopen(req).read()
print result
Does anyone have any idea what I'm doing wrong above? Many thanks for any insights
Experiencing the same problem here. Based on Get access token from Paypal in Python - Using urllib2 or requests library working python code is:
import urllib
import urllib2
import base64
token_url = 'https://api.sandbox.paypal.com/v1/oauth2/token'
client_id = '.....'
client_secret = '....'
credentials = "%s:%s" % (client_id, client_secret)
encode_credential = base64.b64encode(credentials.encode('utf-8')).decode('utf-8').replace("\n", "")
header_params = {
"Authorization": ("Basic %s" % encode_credential),
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json"
}
param = {
'grant_type': 'client_credentials',
}
data = urllib.urlencode(param)
request = urllib2.Request(token_url, data, header_params)
response = urllib2.urlopen(request).open()
print response
The reason, I believe, is explained at Python urllib2 Basic Auth Problem
Python libraries, per HTTP-Standard, first send an unauthenticated request, and then only if it's answered with a 401 retry, are the correct credentials sent. If the servers don't do "totally standard authentication" then the libraries won't work.