Wil
Wil

Reputation: 115

Retrieve SocialAccount token and refresh token from django-allauth

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

Answers (2)

dacx
dacx

Reputation: 844

Here is what I had to do:

  1. Set AUTH_PARAMS['access_type'] to offline for the Google app like so:
SOCIALACCOUNT_PROVIDERS = {
    'google': {
        'SCOPE': [
            ...
        ],
        'AUTH_PARAMS': {
            'access_type': 'offline',
        }
    },
  1. And, then do a FULL NEW AUTHENTICATION. Google knows that your account has access to the app and thus only 'nods you by'. Manually revoke the token you see in django admin by visiting the following URL via your web browser:
https://accounts.google.com/o/oauth2/revoke?token=ey...
  1. Connect your Google account anew.

Upvotes: 2

Sam Texas
Sam Texas

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

Related Questions