Use AllAuth authentication to authenticate current user to another API

441 views Asked by At

I'm beginning with Oauth2 authentication with django allauth. I followed this tutorial The authentication with Google OAuth is working Now I'm wondering how to use this authenticated User to use another API that is using Google Oauth too by using information of the already logged in user. I imagine that the process is based on using the AccessToken used at first app authentication to log in the API, API that will validate this accessToken to Google too. But honestly I don't see at all the way to implement this behaviour Is there some explanation or tutorial or documentation describing this king of architecture ? or maybe I'm wrong on the way and there is a better way to do that ? Thank you in advance RV

1

There are 1 answers

2
Philippe Sisowath On BEST ANSWER

Connect to other Google APP

To coonect to other Google solution, you can try to use google-auth.

1 Install google-auth

 pip install google-auth

2 Get the token from the user logged in using Django-AllAuth with his Google Account. Django AllAuth stores the access token in the SocialToken model

from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    access_token = request.user.socialaccount_set.get(provider='google').socialtoken_set.get().token
    # Now you have the access token to use for API requests

3 Get token and make requests to the desired Google API using the access token. Here's an example using the Google Calendar API

from google.oauth2 import service_account
from googleapiclient.discovery import build

@login_required
def my_view(request):
    access_token = request.user.socialaccount_set.get(provider='google').socialtoken_set.get().token

    # Create a credentials object using the access token
    credentials = service_account.Credentials.from_authorized_user_info(
        {'access_token': access_token},
        ['https://www.googleapis.com/auth/calendar']
    )

    # Build the Google Calendar API service
    service = build('calendar', 'v3', credentials=credentials)

    # Now you can make requests to the Google Calendar API using the service object
    # For example, list the user's calendars
    calendars = service.calendarList().list().execute()
    for calendar in calendars['items']:
        print(calendar['summary'])

Some ressources:

EDIT:

Sign In to other app using OAUTH2

To give a general overview of how to connect to another app, here's 2 example:

StackExchange

Reddit