How to use Google Oauth2 access_token? - python

I'm building a SSO setup for a web app. I can login known users and create new unknown users via https://www.googleapis.com/oauth2/v1/userinfo.
I get back a response like this:
{
"access_token":"1/fFAGcxxxxxxxxxxxxxxxxxxx",
"expires_in":3920,
"token_type":"Bearer",
"refresh_token":"1/xEoDL4iW3cxlI7yDbSRFYxxxxxxxxxxxxxxxxxxx"
}
So I get the user:
url = 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=%s' % a['access_token']
req = urllib2.Request( url )
opener = urllib2.build_opener( urllib2.HTTPSHandler( debuglevel=0 ) )
req = opener.open( req )
reply = req.read()
req.close()
a = json.loads( reply )
That gives me the user's info and permission to access their GMail via
my initial scope. But does this method of acquiring the user allow access to the user's
GMail via imap?
http://code.google.com/apis/gmail/oauth/protocol.html
Does the access_token I'm getting allow access to that? I don't see where to use the 'access_token' now that I have it.

(Not sure if you still need an answer to this, but just in case...)
While most Google APIs can now authenticate using OAuth2, the Google IMAP client only supports OAuth 1. This requires not only an access token, but also a token 'secret'; you don't get that with the OAuth2 response (since you don't need it), which means it's pretty much useless to you.
What you can do is use OAuth 1; this is still supported by Google, although it doesn't have all the bells and whistles of OAuth2. The details of using it are at the link you mentioned (which now redirects to https://developers.google.com/google-apps/gmail/oauth_protocol). I would strongly recommend you use a known library for this, such as python-oauth2 (which, despite the name, uses OAuth 1).

Related

Why do I keep on getting GET request error from GitHub API

I'm trying to learn the requests library in python and I'm following a guide. I'm sending a get request to api.github.com/user but I keep on getting a Status Code of 401. For username, I was using my email at first, but I thought that was what was making it fail so I changed it to my GitHub username and it still doesn't work. Is there anything I'm doing wrong or are there solutions?
import requests
from getpass import getpass
response = requests.get(
"https://api.github.com/user",
auth=('username', getpass())
)
print(response)
You can no longer authenticate to the GitHub API using Basic authentication (a username and password). That ability has been removed. This API endpoint requires authentication because it tells you the current user, and when you're not logged in, there is no current user.
You'll need to generate a personal access token with the appropriate scopes and use it to authenticate to the API instead. You can also use an OAuth token if you're using an OAuth app, but it doesn't sound like you need that in this case.

How do I get a DocuSign Monitor API access token

I am trying to get an access token to access the DocuSign Monitor API via the JWT grant method as it states in the documentation for the DocuSign Monitor API. Here is a snippet of my test script:
def create_jwt(self):
epoch_time = int(time.time())
priv_key = self.get_rsa(self.privkey_path)
pub_key = self.get_rsa(self.pubkey_path)
body = {"iss": self.iss,
"iat": epoch_time,
"exp": (epoch_time + 3000),
"aud": 'account-d.docusign.com',
"scope": "monitor"}
encoded = jwt.encode(body, priv_key, algorithm='RS256')
# decoded = jwt.decode(encoded, pub_key, audience='account-d.docusign.com', algorithm='RS256')
return encoded
def request_access_token(self, encoded_token):
url = 'https://account-d.docusign.com/oauth/token'
data = {'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
'assertion': encoded_token}
response = requests.post(url=url, data=data)
return response.text
request_access_token returns:
{"error":"invalid_scope"}
As far as I can tell I am following the documentation correctly. Using these functions I am able to successfully generate an access token for other scopes such as signature etc. Is there some problem with developer accounts requesting access to the monitor scope since it is a beta feature? What would a valid request to 'lens.docusign.net/api/v1.0/monitor/organization/{{organizationId}}' look like? I assume one needs to acquire an access token before attempting to make requests to the monitor API? I can't tell where I'm going wrong here. Any help would be greatly appreciated.
So this API is in beta and we have to personally enable your account to use it.
Use this form to submit a request
More information about this new 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