1

I am trying to generate the Access Token using Refresh token from Google Analytics API. The request which I am trying to send is encrypted using Python libraries. When I run the below code, I am getting

{'error': 'unsupported_grant_type', 'error_description':'Invalid grant_type: '}

When I run this code without encrypting the parameters, my request works fine without any issues and able to get the access token as well. I am not really sure what I am missing here. Kindly help on this issue and suggest some solutions.

        import os
        import requests
        import json
        import base64
        import random
        from Crypto import Random
        from Crypto.Cipher import AES
        from Crypto.Random import get_random_bytes
        from Crypto.Util.padding import pad,unpad
        import secrets
        
        key= os.urandom(16)
        iv = Random.new().read(AES.block_size)
        
        
        def encrypt_data(key, data):
            BS = AES.block_size
            pad = lambda s: s + ((BS - len(s) % BS) * chr(BS - len(s) % BS)).encode()
            cipher = AES.new(key, AES.MODE_CBC, iv)
            encrypted_data = base64.b64encode(cipher.encrypt(pad(data)))
            return encrypted_data
        
        
        base_url = "https://accounts.google.com"
        client_Id = "XXXXX"
        client_secret = "YYYYY"
        grant_type = "refresh_token"
        refresh_token = "ZZZZZZ"
        access_type="offline"
        
        data = {"grant_type":grant_type,
        "client_id":client_Id,
        "client_secret":client_secret,
        "refresh_token":refresh_token,
        "access_type":access_type
        }
        
    encode_string = json.dumps(data).encode("utf-8")      
    response = requests.post(base_url+"/o/oauth2/token?",params=encrypt_data(key,encode_string)).json()
    print(response.content)
sac
  • 175
  • 2
  • 14
  • any special reason your not using the official library? – Linda Lawton - DaImTo Feb 09 '23 at 06:28
  • @LindaLawton-DalmTo.. thanks for the response. Which official library you are referring to? – sac Feb 09 '23 at 11:50
  • The Google apis python client library. Have you checked the QuickStart for python with Google analytics api https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/installed-py – Linda Lawton - DaImTo Feb 09 '23 at 14:05
  • The documentation for google auth is here: https://developers.google.com/identity/protocols/oauth2/web-server#exchange-authorization-code It doesn't mention anything about encryption. +1 to using the client libraries. – Josh Feb 09 '23 at 19:35

0 Answers0