Skip to content

Instantly share code, notes, and snippets.

@Chitrank-Dixit
Last active September 20, 2019 14:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Chitrank-Dixit/29b44daad1d230d30c04e2d366b61b65 to your computer and use it in GitHub Desktop.
Save Chitrank-Dixit/29b44daad1d230d30c04e2d366b61b65 to your computer and use it in GitHub Desktop.
Google API Oauth Authorization code with PKCE Flow
def base64URLEncode(random_bytes):
return base64.urlsafe_b64encode(random_bytes)
def usha256(buffer):
return sha256(buffer).digest()
client_id = 'your-client-id'
client_secret = 'your-client-secret'
redirect_uri = 'your-redirect-uri'
secret_data = b'your-secret-data'
random_chars = os.urandom(32)
verifier = base64URLEncode(secret_data).rstrip(b'=')
code_challenge = base64URLEncode(usha256(verifier)).rstrip(b'=')
code_challenge_method = "S256"
scope = 'email openid profile'
oauth_resp = requests.get('https://accounts.google.com/o/oauth2/v2/auth', params={
'client_id': client_id,
'redirect_uri': redirect_uri,
'response_type': 'code',
'scope': scope,
'code_challenge': code_challenge,
'code_challenge_method': code_challenge_method
})
print(oauth_resp.url)
# From the print url there would be a parameter code=...... ,
# copy that code and paste in the input below
code = input('enter code obtained: ')
authorization_url = oauth_resp.url
headers = {'Content-type': 'application/x-www-form-urlencoded'}
token_url = 'https://www.googleapis.com/oauth2/v4/token'
data = {
'code': code,
'client_id': client_id,
'client_secret': client_secret,
'redirect_uri': redirect_uri,
'grant_type': 'authorization_code',
'code_verifier': verifier
}
token_resp = requests.post(token_url, data=data, headers=headers)
# access token , refresh token , token expiration are the data here
# which can be used further to access the user information
print(token_resp)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment