5

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.

Simon

Simon
  • 165
  • 9
  • 1
    You can authorize the `http` client with your valid `access token` (and probably `refresh_token` + refresh uri) and give that to the client library instead of a credentials object. Or you can build a credential object using the tokens and the refresh uri. Either way, you pass one to the [`build`](https://google.github.io/google-api-python-client/docs/epy/googleapiclient.discovery-pysrc.html#build_from_document) command. – tehhowch Jul 29 '18 at 17:38
  • 1
    Also see [`AccessTokenCredentials`](https://developers.google.com/api-client-library/python/guide/aaa_oauth#AccessTokenCredentials), and the `Credentials` constructor: https://oauth2client.readthedocs.io/en/latest/_modules/oauth2client/client.html#OAuth2Credentials – tehhowch Jul 29 '18 at 17:46
  • @Simon did you find any solution for this and can you please let me know how did you get the access token of google? – Muhammad Usama Mashkoor Jun 25 '20 at 07:03
  • @usama Sadly i just scraped the project and went to work on something else, sorry. Hope you can manage to find the answer - don't hesitate to post it here if you do ! – Simon Jul 09 '20 at 20:50

1 Answers1

3

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.

eMyx
  • 3
  • 3
ayrunn
  • 41
  • 6