You have to call get_authorization_url
first, which user must open and grant you permissions to access his account, in return you will get a code from redirect_uri
callback's query params, which you can exchange for access_token
:
params = {
'scope': 'email',
'response_type': 'code',
'redirect_uri': redirect_uri,
'access_type': 'offline', # to get refresh_token
}
print google.get_authorize_url(**params)
According to documentation this code should work:
data = {
'code': 'code you got from callback',
'grant_type': 'authorization_code',
'redirect_uri': 'http://localhost/oauth2',
}
response = google.get_raw_access_token(data=data)
In response you will get a JSON data like this:
{
"access_token" : "ya29.AHE<....>n3w",
"token_type" : "Bearer",
"expires_in" : 3600,
"id_token" : "eyJh<...>QwNRzc",
"refresh_token" : "1/X86S<...>Vg4"
}
As you can see there is expires_in
(seconds), you have to store the time when you got the token and compare at later with current time + expires_in
.
If the token expired, you can refresh it with refresh_token
later without asking for user confirmation again:
response = google.get_raw_access_token(data={
'refresh_token': refresh_token,
'grant_type': 'refresh_token',
})
print response.content
Notice, that refresh_token
will only be returned the first time user authorises the app.
See this question for details.
Alas it seems that you can't use get_auth_session
, because internally it only extracts access_token
and everything else is discarded.
If you get access_token
immediately without getting auth code
first, you still get expires_in
in callback. From the docs: