I am trying to complete a story assignment system for my school newspaper in Google App Engine. It'll track deadlines for writers, allow writers to pick up stories, and give an "at a glance" view of the weeks stories. My partner and I are trying to fully integrate it with our newspapers Google Apps installation. Oh, and we have to use 3 legged Oauth because we don't have Google Apps Premier.
In that endeavor, I stumbled upon Aeoid and was able to follow the instructions to make federated login work. It's very cool!
Where I'm running into trouble is using Oauth to get a list of the users google documents. I have a test page set up here: mustrun.cornellsun.com/test. It is giving me errors - I've copied them at the bottom of this mail. I don't know if this has to do with my consumer secret (should I be using the key I get from google marketplace? or should I be using the key I get from the manage domains page?). Right now I'm using the key I got from the manage domains page
Also complicating this is that the actual appspot domain is mustrun2sun [].appspot[too new can't post more than one link].com, but I set it up in google apps so that only users from my domain can log in and also so that the app is deployed on my domain. (app is deployed as must[]run[].corn[]ellsun[].[]com & everything refers to it as such, even in the manage domains thing.)
I'm using GDClient 2.0 classes so I'm fairly sure that everything should work as planned... i.e. I'm not using the old service stuff or anything. I've used htt[]p:/[]/k[]ing[]yo-bachi.blog[]spot.c[]om/2010/05/gaego[]ogleoauth.ht[]ml as a bit of a template for my Oauth "dance" because the Google examples are out of date & use the old Google data 1.0 library - I think.
The error that I'm getting when I go to my test page is
Traceback (most recent call last):
File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 511, in __call__
handler.get(*groups)
File "/base/data/home/apps/mustrun2sun/1.341947133742569880/main.py", line 170, in get
feed = client.GetDocList(auth_token=gdata.gauth.AeLoad(users.get_current_user().user_id())) #auth_token=TOKEN
File "/base/data/home/apps/mustrun2sun/1.341947133742569880/gdata/docs/client.py", line 141, in get_doclist
auth_token=auth_token, **kwargs)
File "/base/data/home/apps/mustrun2sun/1.341947133742569880/gdata/client.py", line 635, in get_feed
**kwargs)
File "/base/data/home/apps/mustrun2sun/1.341947133742569880/gdata/client.py", line 308, in request
response, Unauthorized)
Unauthorized: Unauthorized - Server responded with: 401, <HTML>
<HEAD>
<TITLE>Token invalid - Invalid AuthSub token.</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Token invalid - Invalid AuthSub token.</H1>
<H2>Error 401</H2>
</BODY>
</HTML>
Also, since this is hard w/o any source code, below is the relevant code:
import gdata.auth
import gdata.gauth
import gdata.docs.client
import gdata.docs.data
import gdata.docs.service
import gdata.alt.appengine
from aeoid import middleware, users
class GetOauthToken(webapp.RequestHandler):
def get(self):
user_id = users.get_current_user().user_id()
saved_request_token = gdata.gauth.AeLoad("tmp_"+user_id)
gdata.gauth.AeDelete ("tmp_" + user_id)
request_token = gdata.gauth.AuthorizeRequestToken(saved_request_token, self.request.uri)
#upgrade the token
access_token = client.GetAccessToken(request_token)
#save the upgraded token
gdata.gauth.AeSave(access_token, user_id)
self.redirect('/test')
class Test(webapp.RequestHandler):
def get(self):
TOKEN = gdata.gauth.AeLoad(users.get_current_user().user_id())
if TOKEN:
client = gdata.docs.client.DocsClient(source=SETTINGS['APP_NAME'])
client.auth_token = gdata.gauth.AeLoad(users.get_current_user().user_id()) #could try to put back as TOKEN?
self.response.out.write('moo baby')
client.ssl = True
feed = client.GetDocList(auth_token=gdata.gauth.AeLoad(users.get_current_user().user_id())) #auth_token=TOKEN
self.response.out.write(feed)
self.response.out.write('moo boobob')
self.response.headers['Content-Type'] = 'text/plain'
for entry in feed.entry:
self.response.out.writeln(entry.title.text)
else:
# Get unauthorized request token
gdata.gauth.AeDelete(users.get_current_user().user_id())
client = gdata.docs.client.DocsClient(source=SETTINGS['APP_NAME'])
client.ssl = True # Force communication through HTTPS
oauth_callback_url = ('http://%s/get_oauth_token' %
self.request.host)
request_token = client.GetOAuthToken(
SETTINGS['SCOPES'], oauth_callback_url, SETTINGS['CONSUMER_KEY'],
consumer_secret=SETTINGS['CONSUMER_SECRET'])
gdata.gauth.AeSave(request_token, "tmp_"+users.get_current_user().user_id())
# Authorize request token
domain = None#'cornellsun.com'
self.redirect(str(request_token.generate_authorization_url(google_apps_domain=domain)))
I've been looking high and low on the web for an answer & I have not been able to find one.
I have a working python App Engine app that uses OpenID, and OAuth to get your google contacts:
http://github.com/sje397/Chess
It is running at:
http://your-move.appspot.com
Note that Aeoid is not needed anymore, since App Engine has built-in OpenID support.
I just found out wasting a couple of hours, that you get a 401 also if the URL is not correct.
In my example, I was doing
.../buzz/v1/activities/#me/#self**?&**alt=json
Instead of
.../buzz/v1/activities/#me/#self**?**alt=json
I have personally not worked with OAuth, but a few things I noticed that may (or may not) help:
The 401 error is likely an HTTP 401 error, which means that the url was valid but required authentication. This obviously is explained by the failed OAuth attempt, but it also might be important to redirect users who are not logged in to another page.
The error is occurring when you assign your feed variable. Is the auth_token parameter simply supposed to be a username?
3.You are using the line.
gdata.gauth.AeLoad(users.get_current_user().user_id())
frequently. Even though it might not be related to your auth problems, you would probably be better off making this query once and storing it in a variable. Then when you need it again, access it that way. It will improve the speed of your application.
Again, I apologize that I have had no specific OAuth experience. I just tried to scan and find some things that may spark you onto the right path.
Related
I am trying to get my google authentication working on a Django app that is requesting Gmail and Calendar data. I have set up the oAuth API in the Google developer console and linked it with my project, and I've triple-checked that my redirect URI perfectly matches that in the code (No errors with HTTP vs. HTTPS nor any inconsistencies with the slashes). I made sure that my key, secret key, ClientID, and Client Secret are all configured and identical in my Django app's admin page. I have followed many youtube tutorials and searched other questions on stack overflow but Authentication is still not working. I am getting an Error 400: redirect_uri_mismatch. Even though I have checked many times to confirm that they are the same.
From all the tutorials, I have learned that there are two main origins for this error:
Server sided (can be fixed in the cloud hosting developer console)
Client sided (can be fixed by altering the code)
Both of these errors have their own individualized messages saying what type of mismatch it is.
Mine, however, says this: You can't sign in to this app because it doesn't comply with Google's OAuth 2.0 policy. \n\nIf you're the app developer, register the redirect URI in the Google Cloud Console.
Here is a photo of the error
[![Google Authentication error message][1]][1]
from django.shortcuts import render, redirect
from django.http import HttpRequest
from google_auth_oauthlib.flow import Flow
from google.auth.transport.requests import Request
from googleapiclient.discovery import build
from .models import CredentialsModel
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
import os
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE'] = '1'
#Scopes are what we should be allowed to access
SCOPES = ['https://mail.google.com/', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', 'openid']
"""
IF HAVING ISSUES WITH ANON USER:
Make sure you are on 127.0.0.1:8000, not localhost, both from the test-page and
the callback page. For some reason they are treated as different sessions and thus will have
issues maintaining a logged in user
"""
def oauth2callback(request):
activeUser = request.user
#URL is what we need to use for authentication
authorization_response = request.build_absolute_uri()
flow = Flow.from_client_secrets_file(
settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON,
scopes=SCOPES,
#This is where we are redirected after authentication
redirect_uri='http://127.0.0.1:8000/google/oauth2callback')
#Now get proper token
flow.fetch_token(authorization_response = authorization_response)
#print(request.user)
#Now save in our database
#print(flow.credentials)
try :
my_credential = CredentialsModel.objects.get(pk = activeUser)
except ObjectDoesNotExist:
CredentialsModel.objects.create(id = activeUser, credential = flow.credentials)
else:
my_credential.credential = flow.credentials
my_credential.save()
return redirect(flow.redirect_uri) #activeUser.get_absolute_url())
[1]: https://i.stack.imgur.com/2HXGP.png
google's documentation is not clear on this part (probably a bug on google's end too):
go to your GCP console, under OAuth consent screen, when the Publishing status is In production, we can still put http://localhost:8080/oauth-authorized/google under the Authorized redirect URIs without triggering the red error message saying Invalid Redirect. However, it doesn't work unless the app is in Testing status.
so in order to test your app at http://127.0.0.1:8000, you need to bring your GCP app to Testing status
hey i was dealing with this problem in ASP.Net MVC,
i think the reason would be the same in php but anyways,
Make sure to copy that url in ur below img to Authorized redirect URIs in OAuth 2.0 Client IDs in Google cloud console.
Check if you are logged in to your google account.
I was using google chrome browser and turns out I was logged out of Gmail as the session expired and when I logged into Gmail and the issue was resolved
In my case, it working in development environment and not in production environment. Enabling API KEY for production resolved the issue.
Copy the url that comes with the error message you get and add it to the authorize redirect uris in your google cloud console
In my case I needed to change my redirect URI from
https://{{my-url}}/google/endpoint
To
https://www.{{my-url}}/google/endpoint
I have a Json service file, and a service account that already accesses translate and sheets, but it will not access user lists. The result is either 400 showing its confused or 401 saying its not authorized. Examples are usually about client involved OAuth processes, where I need server to server. I have enabled that "Enable G Suite domain-wide delegation" feature on the service account too.
I read and tried the JWT method, but I get the same error responses.
https://developers.google.com/identity/protocols/oauth2/service-account#python_2
My goal is to call either one of these end points
https://www.googleapis.com/admin/directory/v1/users
https://www.googleapis.com/admin/directory/v1/users.readonly
Any direction would be greatly appreciated.
UPDATE1:
This is using the Jwt token approach which yields error 401.
with open(CLIENT_SECRET_FILE, "r+") as fh:
config = json.load(fh)
iat = time.time()
exp = iat + 3600
payload = {'iss': config['client_email'],
'sub': config['client_email'],
'aud': 'https://www.googleapis.com/',
'iat': iat,
'exp': exp}
additional_headers = {'kid': config['private_key_id']}
signed_jwt = jwt.encode(payload, config['private_key'], headers=additional_headers,
algorithm='RS256')
url = 'https://www.googleapis.com/admin/directory/v1/users'
headers = {"Authorization": "Bearer " + signed_jwt}
r = requests.get(url, headers=headers)
I have also tried
scopes = ['https://www.googleapis.com/auth/admin.directory.user']
credentials = ServiceAccountCredentials.from_json_keyfile_name(CLIENT_SECRET_FILE, scopes=scopes)
service = build('admin', 'directory_v1', credentials=credentials)
results = service.users().list().execute()
UPDATE2:
This link has great information and simple code to review. As much as I tried to avoid impersonation, the AdminSDK requires it. That makes integrations a bit awkward in my view. In addition, the issue I also faced was the Domain-Wide-Delegation screen in the Google Workspace Admin can get messed up. Deleting the entry and recreating it fixed the forever 403 error I kept getting no matter what I had tried.
https://gist.github.com/lewisrodgers/fa766ebd37c1397d3a014eb73805edd1
You need to incorporate into your code impersonation, so that the service account acts on behalf of the admin
Because only admins have authroization to access Resource: users.
For impersonation in Python you need to implement the additional line
delegated_credentials = credentials.with_subject('admin#example.org')
The link below has great information and simple code to review. As much as I tried to avoid impersonation, the AdminSDK requires it. That makes integrations a bit awkward in my view.
In addition, the issue I also faced was the Domain-Wide-Delegation screen in the Google Workspace Admin that messed up. After much digging over weeks, I found a simple solution of deleting and recreating the client entry in that screen. It fixed the never ending 403 error that hit every test I tried that should have worked and did for many others.
This seems to be the only API set by Google that requires impersonation, and is annoying when attempting to create a SaaS solution.
Really basic, trimmed examples, and decent article references.
https://gist.github.com/lewisrodgers/fa766ebd37c1397d3a014eb73805edd1
I am working to create a pipeline with the spotify API that logs my streaming history. I am planning to automate it by uploading it as a lambda function and scheduling it to run every few hours. I have everything mostly in order, except for that on the first run the API requires web authentication. Here is my code:
import spotipy
import spotipy.util as util
import urllib3
un = USERNAME
scope = 'user-read-recently-played'
cid = CLIENT_ID
csid = CLIENT_SECRET_ID
redr = r'http://localhost:8888/callback/'
token = util.prompt_for_user_token(un,scope,cid,csid,redr)
When this is run for the first time, this message pops up:
User authentication requires interaction with your
web browser. Once you enter your credentials and
give authorization, you will be redirected to
a url. Paste that url you were directed to to
complete the authorization.
Opened <LINK HERE> in your browser
Enter the URL you were redirected to:
And then I have to copy the link from my browser into that space. I can get the URL that I need to paste using urllib3:
req_adr = ADDRESS_IT_OPENS_IN_BROWSER
http = urllib3.PoolManager()
resp = http.request('GET',req_adr)
redrurl = resp.geturl()
But I don't know how to pass it into the input prompt from the util.prompt_for_user_token response
Any suggestions would be very welcome.
So it turns out there is a workaround. You can run it one time on a local machine and that generates a a file called .cache-USERNAME. If you include that file in your deployment package you don't have to copy/paste the URL and it is able to be automated with a lambda function in AWS.
I'm trying to get this example to work from https://github.com/ozgur/python-linkedin. I'm using his example. When I run this code. I don't get the RETURN_URL and authorization_code talked about in the example. I'm not sure why, I think it is because I'm not setting up the HTTP API example correctly. I can't find http_api.py, and when I visit http://localhost:8080, I get a "this site can't be reached".
from linkedin import linkedin
API_KEY = 'wFNJekVpDCJtRPFX812pQsJee-gt0zO4X5XmG6wcfSOSlLocxodAXNMbl0_hw3Vl'
API_SECRET = 'daJDa6_8UcnGMw1yuq9TjoO_PMKukXMo8vEMo7Qv5J-G3SPgrAV0FqFCd0TNjQyG'
RETURN_URL = 'http://localhost:8000'
authentication = linkedin.LinkedInAuthentication(API_KEY, API_SECRET, RETURN_URL, linkedin.PERMISSIONS.enums.values())
# Optionally one can send custom "state" value that will be returned from OAuth server
# It can be used to track your user state or something else (it's up to you)
# Be aware that this value is sent to OAuth server AS IS - make sure to encode or hash it
#authorization.state = 'your_encoded_message'
print authentication.authorization_url # open this url on your browser
application = linkedin.LinkedInApplication(authentication)
http_api.py is one of the examples provided in the package. This is an HTTP server that will handle the response from LinkedIn's OAuth end point, so you'll need to boot it up for the example to work.
As stated in the guide, you'll need to execute that example file to get the server working. Note you'll also need to supply the following environment variables: LINKEDIN_API_KEY and LINKEDIN_API_SECRET.
You can run the example file by downloading the repo and calling LINKEDIN_API_KEY=yourkey LINKEDIN_API_SECRET=yoursecret python examples/http_api.py. Note you'll need Python 3.4 for it to work.
I created 2 applications in my Azure directory, 1 for my API Server and one for my API client. I am using the Python ADAL Library and can successfully obtain a token using the following code:
tenant_id = "abc123-abc123-abc123"
context = adal.AuthenticationContext('https://login.microsoftonline.com/' + tenant_id)
token = context.acquire_token_with_username_password(
'https://myapiserver.azurewebsites.net/',
'myuser',
'mypassword',
'my_apiclient_client_id'
)
I then try to send a request to my API app using the following method but keep getting 'unauthorized':
at = token['accessToken']
id_token = "Bearer {0}".format(at)
response = requests.get('https://myapiserver.azurewebsites.net/', headers={"Authorization": id_token})
I am able to successfully login using myuser/mypass from the loginurl. I have also given the client app access to the server app in Azure AD.
Although the question was posted a long time ago, I'll try to provide an answer. I stumbled across the question because we had the exact same problem here. We could successfully obtain a token with the adal library but then we were not able to access the resource I obtained the token for.
To make things worse, we sat up a simple console app in .Net, used the exact same parameters, and it was working. We could also copy the token obtained through the .Net app and use it in our Python request and it worked (this one is kind of obvious, but made us confident that the problem was not related to how I assemble the request).
The source of the problem was in the end in the oauth2_client of the adal python package. When I compared the actual HTTP requests sent by the .Net and the python app, a subtle difference was that the python app sent a POST request explicitly asking for api-version=1.0.
POST https://login.microsoftonline.com/common//oauth2/token?api-version=1.0
Once I changed the following line in oauth2_client.py in the adal library, I could access my resource.
Changed
return urlparse('{}?{}'.format(self._token_endpoint, urlencode(parameters)))
in the method _create_token_url, to
return urlparse(self._token_endpoint)
We are working on a pull request to patch the library in github.
For the current release of Azure Python SDK, it support authentication with a service principal. It does not support authentication using an ADAL library yet. Maybe it will in future releases.
See https://azure-sdk-for-python.readthedocs.io/en/latest/resourcemanagement.html#authentication for details.
See also Azure Active Directory Authentication Libraries for the platforms ADAL is available on.
#Derek,
Could you set your Issue URL on Azure Portal? If I set the wrong Issue URL, I could get the same error with you. It seems that your code is right.
Base on my experience, you need add your application into Azure AD and get a client ID.(I am sure you have done this.) And then you can get the tenant ID and input into Issue URL textbox on Azure portal.
NOTE:
On old portal(manage.windowsazure.com),in the bottom command bar, click View Endpoints, and then copy the Federation Metadata Document URL and download that document or navigate to it in a browser.
Within the root EntityDescriptor element, there should be an entityID attribute of the form https://sts.windows.net/ followed by a GUID specific to your tenant (called a "tenant ID"). Copy this value - it will serve as your Issuer URL. You will configure your application to use this later.
My demo is as following:
import adal
import requests
TenantURL='https://login.microsoftonline.com/*******'
context = adal.AuthenticationContext(TenantURL)
RESOURCE = 'http://wi****.azurewebsites.net'
ClientID='****'
ClientSect='7****'
token_response = context.acquire_token_with_client_credentials(
RESOURCE,
ClientID,
ClientSect
)
access_token = token_response.get('accessToken')
print(access_token)
id_token = "Bearer {0}".format(access_token)
response = requests.get(RESOURCE, headers={"Authorization": id_token})
print(response)
Please try to modified it. Any updates, please let me know.