Reputation: 115
I am trying to interface with the Gmail API using Django and django-allauth for authentication. I have configured my project according to the django-allauth documentation for Google. I am able to log in with a Google account and can see the account details on the Django admin page. Still I am unable to retrieve the token and refresh token to create a google.oath2.credentials.Credential
object to pass to the Gmail API.
Here is my current attempt:
from allauth.socialaccount.models import SocialApp, SocialAccount
from google.oauth2.credentials import Credentials
def get_credentials(request):
app = SocialApp.objects.get(provider='google')
account = SocialAccount.objects.get(user=request.user)
user_tokens = account.socialtoken_set.first()
creds = Credentials(
token=user_tokens.token,
refresh_token=user_tokens.refresh_token,
client_id=app.client_id,
client_secret=app.client_secret
)
return creds
However, the user_token
object is coming back as None
, so the account.socialaccount_set
must be empty. I'm not sure how this is possible if the request.user
is correctly populated (I have verified that it is correct).
Am I missing something? Any help is appreciated!
Upvotes: 0
Views: 3309
Reputation: 844
Here is what I had to do:
SOCIALACCOUNT_PROVIDERS = {
'google': {
'SCOPE': [
...
],
'AUTH_PARAMS': {
'access_type': 'offline',
}
},
https://accounts.google.com/o/oauth2/revoke?token=ey...
Upvotes: 2
Reputation: 1275
I've been looking into this as well. There is a very specific part of the docs:
https://django-allauth.readthedocs.io/en/latest/providers.html#django-configuration
You must set AUTH_PARAMS['access_type'] to offline in order to receive a refresh token on first login and on reauthentication requests (which is needed to refresh authentication tokens in the background, without involving the user’s browser). When unspecified, Google defaults to online.
Have you checked this in your settings.py
?
Upvotes: 0