pythondjangodjango-rest-frameworkgoogle-apidj-rest-auth

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 https://github.com/googleapis/google-api-python-client/blob/main/docs/oauth.md 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(
                    file_path,
                    scopes=SCOPES,
                    redirect_uri='https://example.com'
        )
        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:

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

Thanks!


Solution

  • 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']])