Exchange authorization code for refresh and access tokens - google - python - 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!

Related

Authorisation issues for OAuth API using Python (Yahoo Japan)

I'm not super familiar with APIs and have only worked with a few before where they have been quite simple to use (generate access token on website, use access token as header in get request to pull data).
I'm trying to pull data from an account on the Yahoo Japan Ads platform. Here is the documentation/tutorial I've been following: https://ads-developers.yahoo.co.jp/developercenter/en/startup-guide/api-call.html
I've tried a few different pieces of code, the link states the auth url at the top: https://biz-oauth.yahoo.co.jp/oauth
I'm not sure what parameters are required for authorisation but I've tried multiple. Here is a snippet of my code.
import requests
url = 'https://biz-oauth.yahoo.co.jp/oauth'
params = {'client_id' : '1234', 'redirect_uri' : 'oob'}
response = requests.get(url, params = params)
response.status_code
I'm unsure of what to put as the redirect uri as I plan to just pull a report from the platform, the application i have added in platform shows this in the configuration: oob
So i have used oob as the redirect uri. Using the code above, I'm getting a 404 error.
In the initial link where it shows an example, I have tried using that link instead: https://biz-oauth.yahoo.co.jp/oauth/v1/authorize?response_type=code, this also returns a 400 error.
Any help or suggestions on how to do the auth would be appreciated!
Thanks

How to send post to laravel api from python?

This is my python request code.
url = "https://test.com/"
r = requests.get(url, verify=False)
xsrf_token = r.cookies.get("XSRF-TOKEN")
headers = {
'X-XSRF-TOKEN':xsrf_token
}
data = {"account": "O_O#gmail.com", "password": "123123"}
r = requests.post(url+'/app/get/users', verify=False, data = data, headers=headers)
In laravel log, I got
[2019-12-27 16:09:14] local.ERROR: The payload is invalid. {"exception":"[object] (Illuminate\Contracts\Encryption\DecryptException(code: 0): The payload is invalid. at /var/www/html/test/vendor/laravel/framework/src/Illuminate/Encryption/Encrypter.php:195)
[stacktrace]
Have any method to solve that? Thanks.
You can't solve the issue with a static xsrf alone since it's doing its job preventing Cross Site Request Forging wich is exactly what you're doing in that piece of code.
To use a route as an API, the laravel installation needs to be configured that way, so, if needed, a stateless way of authentification is used (jwt for example) instead of the session with xsrf token for post methods.
Basicly if it's not configured to be used as an API, you will not be able to use it as an API.

How to correctly use PowerBI's REST API?

I have been working on using the powerbi REST API and I haven't been able to properly make use of it. I made use of this and I was able to register an app and get as far as getting an access token, but still I get 401 statuses on my requests.
My major points of confusion are with regards to the app registration:
1) I am trying to read and write data from a python script. Is this a Native-App or a Web Side Server?
2) What is the meaning of the redirect and home urls on the app registration page? I am currently using my localhost:5000 with different /paths. Could this be the source of the issue?
3) My research indicates that there should be some sort of login interaction. I don't have one, is this an indication that something isn't being done properly?
My code is as follows:
import adal
import requests
AUTHORITY_URL = 'https://login.microsoftonline.com/{my_company}.onmicrosoft.com'
RESOURCE = 'https://analysis.windows.net/powerbi/api'
CLIENT_ID = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
CLIENT_SECRET = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
def make_headers(access_token):
return {
'Authorization': "Bearer {}".format(access_token)
}
context = adal.AuthenticationContext(AUTHORITY_URL)
token = context.acquire_token_with_client_credentials(RESOURCE, CLIENT_ID, CLIENT_SECRET)
access_token = token['accessToken']
headers = make_headers(access_token)
url = "https://api.powerbi.com/v1.0/myorg/datasets"
resp = requests.get(url, headers=headers)
As I said above this works to give me an access token though a get a status 401 response on the request and there is no sign in prompt.
Any help/guidance would be tremendously appreciated.
1) In your case you should register a Native app.
2) Native apps has only Redirect URI. Redirect URI gives AAD more details about the specific application it authenticates. For Native apps you should set it to https://login.live.com/oauth20_desktop.srf.
3) It's hard to say why you are getting Unauthorized response. Check what rights you gave to your application - does it has rights to read or write all datasets? Try to decode the access token at https://jwt.io and look at scp - does it contain "Dataset.Read.All" or "Dataset.ReadWrite.All"?

Python Requests - Azure Graph API Authentication

I am trying to access the Azure AD Graph API using the Python requests library. My steps are to first get the authorization code. Then, using the authorization code, I request an access token/refresh token and then finally query the API.
When I go through the browser, I am able to get my authorization code. I copy that over to get the access token. However, I've been unable to do the same with a Python script. I'm stuck at the part where I get the authorization code.
My script returns a response code of 200, but the response headers don't include that field. I would've expected the new URL with the code to be in the response headers. I would have also expected a response code of 301.
Does anyone know why my response headers don't have the auth code? Also, given the auth code, how would I pull it out to then get the access/refresh tokens using Python?
My code is below:
import requests
s = requests.Session()
s.auth = (USERNAME, PASSWORD)
# Authorize URL
authorize_url = 'https://login.microsoftonline.com/%s/oauth2/authorize' % TENANT_ID
# Token endpoint.
token_url = 'https://login.microsoftonline.com/%s/oauth2/token' % TENANT_ID
payload = { 'response_type': 'code',
'client_id': CLIENT_ID,
'redirect_uri': REDIRECT_URI
}
request = s.get(authorize_url, json=payload, allow_redirects=True)
print request.headers
It looks that you are implementing with Authorization Code Grant Flow via python requests. As the flow shows, the response of the request of authorize_url will redirect to a SSO page of your AD tenant. After your user login on, it will redirect to the location which set in redirect_uri with code as the URL parameters. E.G. http://localhost/?code=AAABAAAAiL...
And your code seems cannot simply display a html page with JavaScript allowed, so it will not redirect to the login on page.
So you can refer to # theadriangreen’s suggestion to implement with a python web server application.
Otherwise, you can refer to Microsoft Azure Active Directory Authentication Library (ADAL) for Python, which is a python package for acquiring access token from AD and can be easily integrated in your python application.

Flickr OAuth from Google App Engine Python

I have a weird problem with Flickr OAuth on Google App Engine:
I'm requesting for oauth token and secret from Flickr using the code attached.. it fails most of time when tested on App Engine.. Flickr returns a page saying
"Flickr has the hiccups. We're looking into the problem right now..."
At first I thought it might be the problem with Flickr.. but then if I copied the URL into chrome directly, I could get the oauth token and secret..
So I thought it could be the problem with my code fetching the URL.. but in fact, with the same piece of code, I'm also able to get token and secret at localhost..
Now I'm really confused.. because this used to work perfectly until recently.. is there any update on App Engine dev server that might cause the problem? Please help!!!
url = "http://www.flickr.com/services/oauth/request_token"
params = {
"oauth_timestamp": str(int(time())),
"oauth_signature_method": "HMAC-SHA1",
"oauth_version": "1.0",
"oauth_nonce": sha1(str(random())).hexdigest(),
"oauth_callback": API_CALLBACK,
"oauth_consumer_key": API_KEY,
}
# Setup the Consumer with the key-secret given by Flickr
consumer = oauth2.Consumer(key=API_KEY, secret=API_SECRET)
# Create request
req = oauth2.Request(method="GET", url=url, parameters=params)
# Create signature
signature = oauth2.SignatureMethod_HMAC_SHA1().sign(req, consumer, None)
# Add the Signature to the request
req['oauth_signature'] = signature
h = httplib2.Http()
resp, content = h.request(req.to_url(), "GET")
Update: I changed the code a little bit, keep requesting if I don't get the token (given a max try allowed). It works... still, it is very annoying that I have to write such work-around. Would appreciate if better alternative is available!
You need to use https instead of http (see the comment thread above)

Categories

Resources