I want to code that post facebook. So I decided to use python-sdk (https://github.com/pythonforfacebook/facebook-sdk).
Then I hit a problem.
graph = facebook.GraphAPI(oauth_access_token)
How can I get this "oauth_access_token"?
You need to use an authorization flow. Access tokens are the keys used after getting proper authorization.
An access token is an opaque string that identifies a user, app, or
page and can be used by the app to make graph API calls. Access tokens
are obtained via a number of methods, each of which are covered later
in this document. The token includes information about when the token
will expire and which app generated the token. Because of privacy
checks, the majority of API calls on Facebook need to include an
access token.
There are various ways to obtain an access token all explained in https://developers.facebook.com/docs/facebook-login/access-tokens/
For testing, one must create an app at https://developers.facebook.com/apps and can be issued an access token at https://developers.facebook.com/tools/access_token
Here is a way to get the user access token :
instance = UserSocialAuth.objects.get(user=request.user, provider='facebook')
token = instance.tokens
graph = facebook.GraphAPI(token['access_token'])
Maybe you've already figured this out, just in case somebody else is looking for it
Related
According to the documentation, I can either send the request with authorization (token) in order to get all of my gists, or anonymously and I will get public popular gists.
My Python code is:
url = "https://api.github.com/gists"
with Get(
url,
headers={"Accept": accept},
params={"since": since, "per_page": per_page, "page": page},
auth=("token", token)
) as response:
return response
When token is set to None, I get all public gists (not mine) and when token is set to my OAuth token, I get all of my gists.
However, the issue is that it only gives me my non-secret gists instead of secret and public together.
Initially I was thinking that my token was wrong and therefore I was not getting the secret gists, but turns out that the token is correct (for sure, I can even post new gists) and also has permissions to read/write gists, and that is why it is weird.
The issue is also not related to either params or headers, tested.
Additional Information:
Get is a class which implements a context-manager and sends a get request [link].
After a long research I found out that GitHub's OAuth token from Developer Settings is not enough to perform this action and I need to create a GitHub App in order to extend GitHub.
I used this tool:
https://github.com/defunkt/gist
in order to ask GitHub for such a particular token (which is being used in the GitHub App), and then I started using it, and it worked!
With the new fine grained personal access tokens this can now be done without a GitHub App:
You need to give read-write access to Gists under Account Permissions:
I am currently developing integration for users and groups through Azure AD. I have set up everything to retrieve an access and refresh token upon login, I am only having trouble storing both of them in the sessions. I am assigning the tokens to a session and trying to retrieve them as shown below.
self.session["access_token"] = json.dumps(access_token)
self.session["refresh_token"] = json.dumps(refresh_token)
then I am fetching both tokens on another page, using
access_token = json.loads(self.session.get('access_token'))
refresh_token = json.loads(self.session.get('refresh_token'))
I can only for some reason get the access_token inside the other page, the refresh token is always None. For reference I am using the BaseHandler module on both pages.I was thinking of storing both in the database being a solution, but I want to know if it is possible to configure it in some way to work with self.session. Any help is greatly appreciated!
I am evaluating different options for authentication in a python App Engine flex environment, for apps that run within a G Suite domain.
I am trying to put together the OpenID Connect "Server flow" instructions here with how google-auth-library-python implements the general OAuth2 instructions here.
I kind of follow things up until 4. Exchange code for access token and ID token, which looks like flow.fetch_token, except it says "response to this request contains the following fields in a JSON array," and it includes not just the access token but the id token and other things. I did see this patch to the library. Does that mean I could use some flow.fetch_token to create an IDTokenCredentials (how?) and then use this to build an OpenID Connect API client (and where is that API documented)? And what about validating the id token, is there a separate python library to help with that or is that part of the API library?
It is all very confusing. A great deal would be cleared up with some actual "soup to nuts" example code but I haven't found anything anywhere on the internet, which makes me think (a) perhaps this is not a viable way to do authentication, or (b) it is so recent the python libraries have not caught up? I would however much rather do authentication on the server than in the client with Google Sign-In.
Any suggestions or links to code are much appreciated.
It seems Google's python library contains a module for id token validation. This can be found at google.oauth2.id_token module. Once validated, it will return the decoded token which you can use to obtain user information.
from google.oauth2 import id_token
from google.auth.transport import requests
request = requests.Request()
id_info = id_token.verify_oauth2_token(
token, request, 'my-client-id.example.com')
if id_info['iss'] != 'https://accounts.google.com':
raise ValueError('Wrong issuer.')
userid = id_info['sub']
Once you obtain user information, you should follow authentication process as described in Authenticate the user section.
OK, I think I found my answer in the source code now.
google.oauth2.credentials.Credentials exposes id_token:
Depending on the authorization server and the scopes requested, this may be populated when credentials are obtained and updated when refresh is called. This token is a JWT. It can be verified and decoded [as #kavindu-dodanduwa pointed out] using google.oauth2.id_token.verify_oauth2_token.
And several layers down the call stack we can see fetch_token does some minimal validation of the response JSON (checking that an access token was returned, etc.) but basically passes through whatever it gets from the token endpoint, including (i.e. if an OpenID Connect scope is included) the id token as a JWT.
EDIT:
And the final piece of the puzzle is the translation of tokens from the (generic) OAuthSession to (Google-specific) credentials in google_auth_oauthlib.helpers, where the id_token is grabbed, if it exists.
Note that the generic oauthlib library does seem to implement OpenID Connect now, but looks to be very recent and in process (July 2018). Google doesn't seem to use any of this at the moment (this threw me off a bit).
I am currently using django-social-auth to manage oauth2 registration with google-oauth2 for access to Google Drive. I have added offline access to my extra_arguments. Therefore Google returns a refresh token and it is stored by django-social-auth. The problem is that django-social-auth never uses this refresh token to update the access token. Therefore the access token expires after one hour, and I can't use it to perform offline requests. I want to keep the access_token valid 24/7 so I can keep my database synced with each users Google Drive.
GOOGLE_OAUTH2_AUTH_EXTRA_ARGUMENTS = {'access_type':'offline'}
GOOGLE_OAUTH_EXTRA_SCOPE = ['https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/userinfo.profile']
SOCIAL_AUTH_USER_MODEL = 'accounts.GoogleDriveUser'
SOCIAL_AUTH_EXTRA_DATA = True
SOCIAL_AUTH_SESSION_EXPIRATION = False
Is there a way to force django-social auth to update the access_token every time it expires using the refresh_token. I would love to see an example of how this problem could be solved.
It looks like UserSocialAuth objects now have a .refresh_token() method, which allows you to use .tokens and get the updated token.
There's no way directly implemented in django-social-auth at the moment (I've raised a ticket to track it https://github.com/omab/django-social-auth/issues/492), meanwhile this snippet will do the work, it just need to be improved a little to suite your needs.
Currently am using Graph Explorer to get a short-lived user access token and than converting it to a extended token(60 days) by a call to facepy get_extended_access_token method.
Now. consider the scenario where my user access token becomes invalid because of either user logging out or the token expires itself. So, in both the cases I need to get a new user access token because get_extended_access_token requires access_token so that it can extend it.
So, my question is how to retrieve this token using python? Is there any particular url which I can send a request and it will return a new/updated token in resonse.
Update:
So, after following this post and making a request to
https://graph.facebook.com/oauth/access_token?client_id=xxxx&client_secret=yyyy&grant_type=client_credentials
I got this token which I believe is an app access token
access_token=123456789|12abcdef234 #changed from original
But what I need is an user access token through which I can read my mailbox.
If the access token has expired or been invalidated you need to go back through the Auth Dialog, i.e. a user must manually re-grant access to your application. Retrieving it programmatically defeats the whole purpose of token invalidation/expiry.
Once you get this token, you can then use get_extended_access_token to get the long lived one
App tokens can be used to publish a post on the user's behalf.