Transform Curl Oauth2 to Python Script - python

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)

Related

Unable to post authorization header in python requests

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}

How to Resolve Status 401 in HTTP Post Request Python?

I am trying to make an http post request in Python. The http that I am posting to requires an authorization. For security, I have replaced the real url, data and authorization. When I run the code below with the correct url, data body and authorization I get status 401. That would imply that the authorization is not correct. Is there another way I should be adding authorization, headers and body to my http post request so that the post is successful? The authorization password is correct and works in Postman, so it's contents is not the issue--I'm wondering if the format is. Thanks in advance!
import requests
from requests.auth import HTTPBasicAuth
def post():
url = 'http://somelongurl'
headers = {'Content-Type': 'application/json'}
auth = HTTPBasicAuth('Authorization', 'PASSWORD')
data = {"ProductID" : "ABCDEFG",
"ClientID": "10000",
"SerialNumber": "1234567890"}
req = requests.post(url, headers=headers, data=data, auth=auth)
return req
This was resolved by including the authorization in the headers and changing the data as type json as follows: https://postimg.cc/3y7B6fvL

Response status code 400 when using python module Requests with Sitescout API

I have a client id and client secret and am attempting to generate an auth token by following Sitescout's api docs. I'm using python module Requests and am getting a 400 status code back, aka malformed request, but I can't seem to figure out why.
My code:
import requests
url = "https://api.sitescout.com/oauth/token"
headers = {
"Host": "api.sitescout.com",
"Authorization": "Basic YmVldGhvdmVuOmxldG1laW4=",
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json",
"Content-Length": "41"
}
# Do the HTTP request
response = requests.post(url, headers=headers)
response.status_code
That is the fake base64 Authorization header provided in the docs so this snippet returns a 401 error, aka unauthorized (I have my own auth of course).
Can anyone tell me what's wrong with this?
It has been resolved. I did not put grant_type=client_credentials which, when added, returns a 200.
The docs say "Optionally, you can add form parameter scope to indicate which scopes you are requesting access to; the scope values must be space delimited (e.g., STATS AUDIENCES)." But it is the "&scope=STATS" param that is optional, not all params. The example confused me.
Now my code reads
...
params = { "grant_type" : "client_credentials" }
response = requests.post(url, headers=headers, params=params)
...
which works.

Python: Bad request in POST using requests

I am supposed to send this:
curl --header "Content-Type: text/plain" --request POST --data "ON" example.com/rest/items/z12
Instead, I am sending this:
import requests
headers = {"Content-Type": "text/plain"}
url = 'http://example.com/rest/items/z12'
_dict = {"ON": ""}
res = requests.post(url, auth=('demo', 'demo'), params=_dict, headers=headers)
And I am getting an Error 400 (Bad Request?)
What am I doing wrong?
The POST body is set to ON; use the data argument:
import requests
headers = {"Content-Type": "text/plain"}
url = 'http://example.com/rest/items/z12'
res = requests.post(url, auth=('demo', 'demo'), data="ON", headers=headers)
The params argument is used for URL query parameters, and by using a dictionary you asked requests to encode that to a form encoding; so ?ON= is added to the URL.
See the curl manpage:
(HTTP) Sends the specified data in a POST request to the HTTP server, in the same way that a browser does when a user has filled in an HTML form and presses the submit button.
and the requests API:
data – (optional) Dictionary, bytes, or file-like object to send in the body of the Request.
params parameter in the requests.post method is used to add GET parameters to the URL. So you are doing something like this :
curl --header "Content-Type: text/plain" --request POST example.com/rest/items/z12?ON=
You should instead use the data parameter.
import requests
headers = {"Content-Type": "text/plain"}
url = 'http://example.com/rest/items/z12'
res = requests.post(url, auth=('demo', 'demo'), data="ON", headers=headers)
Moreover, if you give a dictionnary to the data parameter, it will send the payload as "application/x-www-form-urlencoded". In your curl command, you send raw string as payload. That's why I changed a bit your example.

Trouble with simple https authentication with urllib2 (to get PayPal OAUTH bearer token)

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.

Categories