How To Make 'access_type=offline' / Server-only Oauth2 Operations On Gae/python?
Solution 1:
Offline access is the default when retrieving tokens; you may have noticed this in the OAuth dialog that comes up:
Perform these operations when I'm not using the application
When your user accepts the OAuth dialog in a method decorated with decorator.oauth_required
the credentials for that user will be stored in the datastore, including the refresh token.
Once you have one of these credentials objects, you can use it so authorize an HTTP object for calling APIS:
importhttplib2http= credentials.authorize(httplib2.Http())
and once authorized, it will do all the work for you. So if the access_token
is expired, the first API response will be a 401
and so the credentials
object will use the refresh_token
to get a new access_token
and make the request again.
If you know the user ID, you can retrieve the credentials
from the datastore as described in How to do OAuth-requiring operations in a GAE Task Queue?:
from oauth2client.appengineimportCredentialsModelfrom oauth2client.appengineimportStorageByKeyName
credentials = StorageByKeyName(
CredentialsModel, user_id, 'credentials').get()
Note/Gotcha:
If a user has already authorized your client ID, the subsequent times you perform OAuth for these users they will not see the OAuth dialog and you won't be given a refresh token. A refresh token can only be given if they go through the OAuth dialog, but since the user had already authorized your client ID, the spec assumes you would already have a refresh token around.
This often comes up when developers are testing OAuth, since they will go through the flow multiple times with a test account and after accepting the 2nd, 3rd, 4th, ... times, they never see the refresh token. A simple way around this is to use approval_prompt=force
as an argument to the OAuth2Decorator
constructor. This will force the OAuth dialog to appear every time you perform OAuth for a user.
However, this will not cause the dialog to show up every time a request is served for a given user; this would be a TERRIBLE user experience. Instead, the SACSID
cookie from the request can be used (by the client library and some App Engine libraries) to determine who the current user is. Once the the library knows that current user, it can get your existing stored token/credentials
for that user from the datastore and no jarring dialog will be needed.
Post a Comment for "How To Make 'access_type=offline' / Server-only Oauth2 Operations On Gae/python?"