Problem with basic auth & json content in requests - python

I am a data analyst moonlighting in some web development, so apologies if this an obvious question, however I couldn't find a direct answer amongst previous questions or requests documentation.
I am trying to access data from an API that requires both basic auth and a content-type: application/json header. I have got this working in postman, but can't transfer to the python requests library - which returns 401.
I have tried passing in the login details (Username, password) as a tuple / list to the relevant dictionary key, however that doesn't work.
What am I missing?
import requests
headers={'Authorization': 'Basic <credentials>', 'Content-Type': 'application/json'}
r = requests.get("https://data.donorfy.com/api/v1/LFJZWVODI2/constituents/ExternalKey/1", headers=headers)
r.json()

Related

Exchange authorization code for refresh and access tokens - google - python

Context
I'm migrating to Google's new auth solution that doesn't require 3rd party cookies using the following guide:
My app is a frontend built in Vue.js and a backend in Python (Flask).
Problem
Once I receive the Authorization token from Google (looks something like 4/0AdQt...bg), I'm unable to exchange it for a refresh & access token.
For Python, the official Google documentation only shows an example that uses Flask (using the Flow object) to request the token and verify it.
I've tried to build a simple POST request with postman
import requests
url = "https://oauth2.googleapis.com/token"
payload='code=4%2F...bg&client_id=92...cac42tg.apps.googleusercontent.com&client_secret=hw...u8D&redirect_uri=https%3A%2F%2Fco...pp&grant_type=authorization_code'
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)
But I get the following unhelpful 400 Bad Request response
{
"error": "invalid_grant",
"error_description": "Bad Request"
}
I tried to change the different form parameters and got different errors (The OAuth client was not found., Unauthorized, invalid_request, ...) so most likely the error is in the actual code.
If anyone has faced a similar issue, I'd love some help!

Python 2.7 HTTP Basic Authentication

maybe someone can help me with this. I'm trying to get a data from a website using Python 2.7, using HTTP Basic Authentication.
The only instructions the website provides is this:
In order for your web service client to authenticate using basic
authentication, the first HTTPS request must include the
"Authorization" header specifying the account credentials to
authenticate with. The header for a such a request would look like
this:
GET /polcs/trade.xml HTTP/1.0
Host: secure.pol.com
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
I tried few things but neither of them works, for example:
import urllib2
import base64
b = base64.encodestring('USERNAME:PASSWORD').replace('\n', '')
conf = {'headers': {'GET': '/polcs/trade.xml HTTP/1.0', 'Authorization': 'Basic ' + b},
'url': 'secure.pol.com'}
datas = None
request = urllib2.Request(conf['url'], datas, conf['headers'])
result = urllib2.urlopen(request)
This one gives me HTTP Error 403:
url = 'https://secure.pol.com/polcs/data.xml'
request = urllib2.Request(url)
b = base64.encodestring('USERNAME:PASSWORD').replace('\n', '')
request.add_header("Authorization", "Basic " + b)
result = urllib2.urlopen(request)
Can someone please tell me where do I make a mistake trying to get that data?
Thank you!

authentication using httplib in python

I am using python 2.7.10. How can I login using httplib connection method.
import httplib
conn = httplib.HTTPConnection("192.18.33.10")
conn.request("POST", "/user/user.form?name=Maharjun&age=23")
res = conn.getresponse()
data = res.read()
What this user.form does is, it will accept some details like name and age from users and server will save them in database. This details can only filled by authenticated users.
I tried some suggestions from python http.requests but those are not working in python-2.7.10.
I know about postman. So, I sent same request in postman using basic authentication method and i converted that into python scripts. In postman we can convert postman-URL into curl/shell/python scripts. So, I converted them into python scripts.
Both are same requests. But I am able to submit the data using postman. But not able to do with python.
postman is giving me a post-man token and basic authentication in headers like below code. is there any mistakes in the code or any suggestions?
import httplib
conn = httplib.HTTPConnection("192.18.33.10")
url = "/user/user.form?name=Maharjun&age=23"
headers = {
'authorization': "Basic some-token",
'cache-control': "no-cache",
'postman-token': "some-token"
}
response = conn.request("POST", url, headers=headers)
print(response.text)
Though it have 'authorization' token I was not able to login by using above code.
can someone help me to write basic authentication using python requests.?

Retrieve access token for Yahoo API using OAuth 2.0 and Python requests

I am trying to retrieve the access token for the Yahoo API, using the explicit grant flow as described in this document:
https://developer.yahoo.com/oauth2/guide/flows_authcode
Everything is fine until Step 4: Exchange authorization code for Access Token
I wrote the following python script to retrieve the code:
import urllib2
import requests
import json
url = 'https://api.login.yahoo.com/oauth2/get_token'
body = "grant_type=authorization_code&redirect_uri=oob&code=************"
headers = {
'Authorization': 'Basic **************',
'Content-Type': 'application/json'
}
r = requests.post(url, data=body, headers=headers)
print r
Note: I replaced sensitive data with "****"
Now, when I execute the script, I only get the "401" error message.
I am 100% sure that the login credentials are fine, so it seems to be related to the way I make the request. It's also the first time that I am using "requests" in python.
Would be great, if you could give me some feedback on the code, and if I am passing the header and body information correctly. I am especially unsure about the passing of the body. The documentation only states the following:
Sample Request Body: grant_type=authorization_code&redirect_uri=https%3A%2F%2Fwww.example.com&code=abcdef
Change your body variable to a dict, i.e.,
body = {
'grant_type': 'authorization_code',
'redirect_uri': 'oob',
'code': '************',
}
No other changes are needed. Hope it helps.
Tough the problem already solved. But may be other user can still get the same 401 error even if they use correct dict as me. The problem is that the code generated in step 2 in the link can be only use ONCE. And this will get the same 401 error. This took me some time to figure it out. Hope this helps others.

How to send GET request including headers using python

I'm trying to build a website using web.py, which is able to search the mobile.de database (mobile.de is a German car sales website). For this I need to use the mobile.de API and make a GET request to it doing the following (this is an example from the API docs):
GET /1.0.0/ad/search?exteriorColor=BLACK&modificationTime.min=2012-05-04T18:13:51.0Z HTTP/1.0
Host: services.mobile.de
Authorization: QWxhZGluOnNlc2FtIG9wZW4=
Accept: application/xml
(The authorization needs to be my username and password joined together using a colon and then being encoded using Base64.)
So I use urllib2 to do the request as follows:
>>> import base64
>>> import urllib2
>>> headers = {'Authorization': base64.b64encode('myusername:mypassw'), 'Accept': 'application/xml'}
>>> req = urllib2.Request('http://services.mobile.de/1.0.0/ad/search?exteriorColor=BLACK', headers=headers)
And from here I am unsure how to proceed. req appears to be an instance with some methods to get the information in it. But did it actually send the request? And if so, where can I get the response?
All tips are welcome!
You need to call req.read() to call the URL and get the response.
But you'd be better off using the requests library, which is much easier to use.

Categories

Resources