How to use credentials obtained from google with google API

Libs: dj-rest-auth + allauth

I. I'm trying to interact with google API with credentials that I use to obtain internal access token. I managed to obtain both code and token but can't find how to use them with google API. The last page I found inapplicable is but probably I'm missing some things.

Here's the view I'm trying to use google API in:

class CreateGoogleDoc(GenericAPIView):

    def get(self, request):
        token = request.query_params['token']
        module_dir = os.path.dirname(__file__)  # get current directory
        file_path = os.path.join(module_dir, 'client_secret.json')
        flow = Flow.from_client_secrets_file(
        credentials = service_account.Credentials.from_service_account_file(file_path, scopes=SCOPES)
        service = build('docs', 'v1', credentials=credentials)

        document = service.documents().create().execute()
        return Response([document['documentId']])

II. While I tried to swap code to internal access token class I got another error:

Error retrieving access token: `{  "error": "invalid_request",  "error_description": "You can't sign in to this app because it doesn't comply with Google's OAuth 2.0 policy for keeping apps secure. You can let the app developer know that this app doesn't comply with one or more Google validation rules."}`

Here's a view that I'm using for swapping:

    adapter_class = GoogleOAuth2Adapter
    callback_url = 'http://localhist:8000/dj-rest-auth/google/'
    client_class = OAuth2Client


Offering a workaround

If you already have a token from the GET response, why are you trying to get credentials from a service account file? Probably there is some wrong configuration there, but if you already have the access token, you can just use it like below and avoid the whole service account token fetching.

from google.oauth2.credentials import Credentials

# ...

def get(self, request):
    token = request.query_params['token']
    credentials = Credentials(token)
    service = build('docs', 'v1', credentials=credentials)

    document = service.documents().create().execute()

    return Response([document['documentId']])


Константы Python: Улучшение управляемости вашего кода

Современный Python: начинаем проект с pyenv и poetry

Настройка проекта Python — виртуальные среды и управление пакетами

Использование requests в Python — тайм-ауты, повторы, хуки

Понимание декораторов в Python

ProcessPoolExecutor в Python: полное руководство

map() против submit() с ProcessPoolExecutor в Python

Понимание атрибутов, словарей и слотов в Python

Полное руководство по slice в Python

Выпуск Django 4.0

Безопасное развертывание приложения Django с помощью Gunicorn, Nginx и HTTPS

Автоматический повтор невыполненных задач Celery

Django REST Framework и Elasticsearch

Докеризация Django с помощью Postgres, Gunicorn и Nginx

Асинхронные задачи с Django и Celery

Релизы безопасности Django: 3.2.4, 3.1.12 и 2.2.24

Выпуски исправлений ошибок Django: 3.2.3, 3.1.11 и 2.2.23

Эффективное использование сериализаторов Django REST Framework

Выпуски безопасности Django: 3.2.2, 3.1.10 и 2.2.22

Выпущенные релизы безопасности Django: 3.2.1, 3.1.9 и 2.2.21

View all tutorials →