RequestError: Unable to upgrade OAuth request token to access token: 400, signature_invalid
base_string:POST&https%3A%2F%2Fwww.google.com%2Faccounts%2FOAuthGetAccessToken&oauth_consumer_key%3Dcalendar-auth.appspot.com%26oauth_nonce%3D646112512717164%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1306760936%26oauth_token%3D4%252F-cP-Ai1NzxDtLehvtzRbGd4SHZ1-%26oauth_verifier%3DPYGMYX8riH9AfpJvTEh_Ztzm%26oauth_version%3D1.0
I am new to google apps development.was trying to implement OAuth in a web application.When i call GetAccessToken() method then it shows the above error.Please help me out frokm this....
I am using the following code... :
class MainHandler(webapp.RequestHandler):
def get(self):
CONSUMER_KEY = 'xyz'
CONSUMER_SECRET = 'xyz'
SCOPES = ['https://docs.google.com/feeds/', 'https://www.google.com/calendar/feeds/'] # example of a multi-scoped token
client = gdata.docs.client.DocsClient(source='xyz')
oauth_callback_url = 'http://%s/get_access_token' % self.request.host
request_token = client.GetOAuthToken(
SCOPES, oauth_callback_url, CONSUMER_KEY, consumer_secret=CONSUMER_SECRET)
memcache.add("rtoken",request_token,3600)
domain = 'default' # If on a Google Apps domain, use your domain (e.g. 'example.com').
url = str(request_token.generate_authorization_url(google_apps_domain=domain))
self.redirect(url)
class AuthToken(webapp.RequestHandler):
def get(self):
client = gdata.docs.client.DocsClient(source='xyz')
saved_request_token = memcache.get("rtoken")
request_token = gdata.gauth.AuthorizeRequestToken(saved_request_token, self.request.uri)
self.response.out.write("Got the token")
access_token = client.GetAccessToken(request_token)
https://www.google.com/accounts/OAuthGetAccessToken
{
oauth_consumer_key=calendar-auth.appspot.com
oauth_nonce=646112512717164
oauth_signature_method=HMAC-SHA1
oauth_timestamp=1306760936
oauth_token=4/-cP-Ai1NzxDtLehvtzRbGd4SHZ1-
oauth_verifier=PYGMYX8riH9AfpJvTEh_Ztzm
oauth_version=1.0
}
I would recommend against posting oauth tokens to the public.
According to http://wiki.oauth.net/w/page/12238555/Signed-Callback-URLs, you should be posting oauth_signature, but I don't see it in the list
Related
Libs: dj-rest-auth + allauth
I. I'm trying to interact with google API with credentials that I use to obtain internal access token. I managed to obtain both code and token but can't find how to use them with google API. The last page I found inapplicable is https://github.com/googleapis/google-api-python-client/blob/main/docs/oauth.md but probably I'm missing some things.
Here's the view I'm trying to use google API in:
class CreateGoogleDoc(GenericAPIView):
...
def get(self, request):
token = request.query_params['token']
module_dir = os.path.dirname(__file__) # get current directory
file_path = os.path.join(module_dir, 'client_secret.json')
flow = Flow.from_client_secrets_file(
file_path,
scopes=SCOPES,
redirect_uri='https://example.com'
)
credentials = service_account.Credentials.from_service_account_file(file_path, scopes=SCOPES)
service = build('docs', 'v1', credentials=credentials)
document = service.documents().create().execute()
return Response([document['documentId']])
II. While I tried to swap code to internal access token class I got another error:
Error retrieving access token: `{ "error": "invalid_request", "error_description": "You can't sign in to this app because it doesn't comply with Google's OAuth 2.0 policy for keeping apps secure. You can let the app developer know that this app doesn't comply with one or more Google validation rules."}`
Here's a view that I'm using for swapping:
GoogleLogin(SocialLoginView):
adapter_class = GoogleOAuth2Adapter
callback_url = 'http://localhist:8000/dj-rest-auth/google/'
client_class = OAuth2Client
Thanks!
Offering a workaround
If you already have a token from the GET response, why are you trying to get credentials from a service account file? Probably there is some wrong configuration there, but if you already have the access token, you can just use it like below and avoid the whole service account token fetching.
from google.oauth2.credentials import Credentials
# ...
def get(self, request):
token = request.query_params['token']
credentials = Credentials(token)
service = build('docs', 'v1', credentials=credentials)
document = service.documents().create().execute()
return Response([document['documentId']])
I want to upload files and create folders on OneDrive with Python. So i copied the code from the OnDrive GitHub GitHub, registered my App at Azure, copied the ID and created an secret. So far so good.
But now, if i run my code. The Browser opens asking for the permission to login automatically, agreed and then i get this error:
Exception: invalid_request
I think it has something to do with the redirect_uri because if i copy this into my browser i cant access it.
Here is my code:
import onedrivesdk
from onedrivesdk.helpers import GetAuthCodeServer
redirect_uri = 'http://localhost:8080/'
client_secret = 'The secret i created on Azure'
scopes=['wl.signin', 'wl.offline_access', 'onedrive.readwrite']
client = onedrivesdk.get_default_client(
client_id='The ID Azure created for me', scopes=scopes)
auth_url = client.auth_provider.get_auth_url(redirect_uri)
#this will block until we have the code
code = GetAuthCodeServer.get_auth_code(auth_url, redirect_uri)
client.auth_provider.authenticate(code, redirect_uri, client_secret)
I also tried it with an Proxy:
import onedrivesdk
from onedrivesdk.helpers import GetAuthCodeServer
from onedrivesdk.helpers import http_provider_with_proxy
redirect_uri = 'http://localhost:8080'
client_secret = 'Secret created with Azure'
client_id = 'ID id got from Azure'
scopes=['wl.signin', 'wl.offline_access', 'onedrive.readwrite']
client = onedrivesdk.get_default_client(client_id, scopes=scopes)
auth_url = client.auth_provider.get_auth_url(redirect_uri)
code = GetAuthCodeServer.get_auth_code(auth_url, redirect_uri)
proxy = {
'http': 'http://localhost:8888',
'https': 'https://localhost:8888'
}
http = http_provider_with_proxy.HttpProviderWithProxy(proxy, verify_ssl=True)
auth = onedrivesdk.AuthProvider(http, client_id, ['onedrive.readwrite'])
client = onedrivesdk.OneDriveClient(redirect_uri, auth, http)
f = onedrivesdk.Folder()
i = onedrivesdk.Item()
i.name = 'New Folder'
i.folder = f
returned_item = client.item(drive='me', id='root').children.add(i)
That gives me this error message:
RuntimeError: Session must be authenticated
before applying authentication to a request.
Your code works - e.g. it sends the info you want to send. However the credentials you have entered will of course return an invalid request - you're trying to connect to azure with:
client_id: 'The ID Azure created for me'
Which I'm pretty sure doesn't exists. The issue is you need an account & pass your script those (valid) account informations to connect to it.
I am writing some code to move files over to OneDrive (enterprise account). My app is authenticated in Azure AD and should have the correct accesses (Files.ReadWrite.All in MS Graph, Sites.ReadWrite.All in Office365 SPO and User.Read in Azure AD).
The code to receive the app token works fine:
import msal
client_id = 'dc185bb*************6bcda94'
authority_host_uri = 'https://login.microsoftonline.com'
discovery_uri = 'https://api.office.com/discovery/'
client_secret = 'VsY7vV**************ToiA0='
tenant = '4a6*********************65079'
authority_uri = authority_host_uri + '/' + tenant
scopes=['https://graph.microsoft.com/.default']
app = msal.ConfidentialClientApplication(
client_id=client_id, authority=authority_uri,
client_credential=client_secret)
result = app.acquire_token_for_client(scopes=scopes)
print(result)
However, when I try to use this token with the OneDrive SDK library it seems like I am not able pass it through:
def __init__(self, http_provider, client_id=None, scopes=None, access_token=None, session_type=None, loop=None,
auth_server_url=None, auth_token_url=None):
"""Initialize the authentication provider for authenticating
requests sent to OneDrive
Args:
http_provider (:class:`HttpProviderBase<onedrivesdk.http_provider_base>`):
The HTTP provider to use for all auth requests
client_id (str): Defaults to None, the client id for your
application
scopes (list of str): Defaults to None, the scopes
that are required for your application
access_token (str): Defaults to None. Not used in this implementation.
The above is from the auth_provider.py part of the onedrivesdk, and clearly states the access_token is not used in the implementation.
Is there another way around this? Or other libraries to use?
You could try to use this Authentication of OneDrive for Business.
import onedrivesdk
from onedrivesdk.helpers import GetAuthCodeServer
from onedrivesdk.helpers.resource_discovery import ResourceDiscoveryRequest
redirect_uri = 'http://localhost:8080'
client_id = your_client_id
client_secret = your_client_secret
discovery_uri = 'https://api.office.com/discovery/'
auth_server_url='https://login.microsoftonline.com/common/oauth2/authorize'
auth_token_url='https://login.microsoftonline.com/common/oauth2/token'
http = onedrivesdk.HttpProvider()
auth = onedrivesdk.AuthProvider(http,
client_id,
auth_server_url=auth_server_url,
auth_token_url=auth_token_url)
auth_url = auth.get_auth_url(redirect_uri)
code = GetAuthCodeServer.get_auth_code(auth_url, redirect_uri)
auth.authenticate(code, redirect_uri, client_secret, resource=discovery_uri)
# If you have access to more than one service, you'll need to decide
# which ServiceInfo to use instead of just using the first one, as below.
service_info = ResourceDiscoveryRequest().get_service_info(auth.access_token)[0]
auth.redeem_refresh_token(service_info.service_resource_id)
client = onedrivesdk.OneDriveClient(service_info.service_resource_id + '/_api/v2.0/', auth, http)
Upload an Item:
returned_item = client.item(drive='me', id='root').children['newfile.txt'].upload('./path_to_file.txt')
For more examples, you can refer to this link.
I'm trying to develop a web app using Google App Engine.
The language i'm using is Python and i'm using the facebook-sdk (https://facebook-sdk.readthedocs.io/en/latest/).
I'm stuck at making the OAuth Facebook login works correctly.
Every single time I attempt to log in to my app using Facebook login i get the error
URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings. Make sure Client and Web OAuth Login are on and add all your app domains as Valid OAuth Redirect URIs.
You can see the screenshot of the error (in the original language) below
That are the settings of my Facebook app
That's the code of my app's RequestHandler which handle the login's requests
import facebook
import os
import webapp2
import urllib
from webapp2_extras import sessions
facebook_ID = 'xxxxxxxxxxx'
facebook_secret = 'xxxxxxxxxxxxxxxxxxxxxx'
facebook_graphUrl = 'https://graph.facebook.com/v2.8'
facebook_redirectUri = 'http://gold-circlet-160109.appspot.com/login/'
facebook_requestCode = 'https://www.facebook.com/v2.8/dialog/oauth?' +
urllib.urlencode(
{'client_id':facebook_ID,
'redirect_uri':facebook_redirectUri,
'scope':'public_profile, email, user_friends'})
def retrieve_access_token(code):
args = {'redirect_uri': facebook_redirectUri,
'client_id': facebook_ID,
'client_secret': facebook_secret,
'code': code}
access_token = urllib.urlopen(facebook_graphUrl + "/oauth/access_token?" + urllib.urlencode(args)).read()
access_token = urlparse.parse_qs(access_token)
return access_token['access_token'][0]
def get_graph_api(token):
if isinstance(token, dict):
return facebook.GraphAPI(token['access_token'])
else:
return facebook.GraphAPI(token)
class BaseHandler(webapp2.RequestHandler):
def dispatch(self):
self.session_store = sessions.get_store(request=self.request)
try:
webapp2.RequestHandler.dispatch(self)
finally:
self.session_store.save_sessions(self.response)
#webapp2.cached_property
def session(self):
return self.session_store.get_session()
class FBLogin(BaseHandler):
def get(self):
code = self.request.get('code')
if self.request.get("code"):
access_tk = retrieve_access_token(code)
facebookObject = get_graph_api(access_tk)
facebookObject = facebookObject.get_object('me')
self.session["ECommerceUser"] = dict(
idSocial = facebookObject['id'],
image='http://graph.facebook.com/'+facebookObject['id']+'/picture?type=square',
username=last_name[0] + " " + last_name[1],
loginMethod=loginMethod
)
self.redirect("/")
else:
self.redirect(facebook_requestCode)
I set the same redirect URI in the URL login request is set in the Facebook Login settings, as you can see from the code above (i followed this guide: https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow)
Any suggestion?
I read the book Introduction to Tornado. It introduces the asynchronous feature of tornado in an application using twitter search API.
The code is as follows:
class IndexHandler(tornado.web.RequestHandler):
#tornado.web.asynchronous
#tornado.gen.engine
def get(self):
query = self.get_argument('q')
client = tornado.httpclient.AsyncHTTPClient()
response = yield tornado.gen.Task(client.fetch,
"http://search.twitter.com/search.json?" + \
urllib.urlencode({"q": query, "result_type": "recent", "rpp": 100}))
...
self.finish()
It uses the v1 twitter API to search a keywork. However, the new v1.1 twitter API forbids the use of non oauth request. As a result, I have to use the oauth library with my consumer key and access key to request the twitter search API.
def request_twitter(url, http_method = 'GET', post_body = '', http_headers = ''):
consumer = oauth.Consumer(key = consumer_key, secret = consumer_secret)
token = oauth.Token(key = access_token, secret = access_secret)
client = oauth.Client(consumer, token)
request = client.request(url, method = http_method, body = post_body, headers = http_headers)
return request
But the oauth client doesn't provide the asynchronous way to request. So I want to know how can I make the asynchronous request using oauth client to twitter API in python? Thanks.
Take a look at the TwitterMixin that is supplied with Tornado and study its code a bit.