Search code examples
pythondjangogoogle-apidjango-allauthgoogle-api-python-client

Use Google API with a token [Django & AllAuth]


I am using AllAuth on my Django app to manage user authentication. With that my users can connect their Google accounts and i get a google API token (with appropriate scopes).

I would like to use that token to access google APIs (Calendar v3 in my case) with that token, as my user already used OAuth2 to sign-in on my website, and gave me access to the calendar API.

Google only gives the full process on their website (from auth to api), is there a way to build my idea, or is it simply impossible?

i have tries drive = build('calendar', 'v3', credentials=credentials) as said here but "credentials" needs to be part of an oauth2client and not just a simple string token.

Thank you for your precious time.


Solution

  • I know its an older question but I finally found something that worked for me. After a successful authentication with allauth, I did this to get the client token and then build the service.

        from googleapiclient.discovery import build
        from google.oauth2.credentials import Credentials
        from allauth.socialaccount.models import SocialToken, SocialApp
    
        ...    
    
        # request is the HttpRequest object
        token = SocialToken.objects.get(account__user=request.user, account__provider='google')
    
        credentials = Credentials(
            token=token.token,
            refresh_token=token.token_secret,
            token_uri='https://oauth2.googleapis.com/token',
            client_id='client-id', # replace with yours 
            client_secret='client-secret') # replace with yours 
    
        service = build('calendar', 'v3', credentials=credentials)
    

    Make sure to have SOCIALACCOUNT_STORE_TOKENS = True as per https://django-allauth.readthedocs.io/en/latest/configuration.html, otherwise you wont have any SocialToken objects.