Search code examples
pythongoogle-cloud-platformgoogle-cloud-pubsuboauth2-playground

How to get an authorization code via HTTP request for Google OAuth 2.0 Playground - Python


I need some help with Google OAuth 2.0 Playground, I hope someone can help. I wonder how to to get an authorization code via HTTP request for Google OAuth 2.0 Playground via python? Is it possible? I'm trying to get an authorization code doing this request :

get

And I was trying to forward the authorization code expected with this post : post

My main code:

auth_url = "https://accounts.google.com/o/oauth2/auth"
access_token_url = "https://accounts.google.com/o/oauth2/token"
callback_url = "https://developers.google.com/oauthplayground"

client_id = 'xxx'
client_secret = xxx'

authorization_redirect_url = auth_url + '?response_type=code&client_id=' + client_id + '&redirect_uri=' + callback_url + '&scope=openid'
authorization_code = requests.get(authorization_redirect_url)

data = {'grant_type': 'authorization_code', 'code': authorization_code, 'redirect_uri': callback_url}
access_token_response = requests.post(access_token_url, data=data, verify=False, allow_redirects=False, auth=(client_id, client_secret))

If I try to run my code I get :

response:
{'Date': 'Wed, 18 Aug 2021 23:35:42 GMT', 'Expires': 'Mon, 01 Jan 1990 00:00:00 GMT', 'Cache-Control': 'no-cache, no-store, max-age=0, must-revalidate', 'Pragma': 'no-cache', 'Content-Type': 'application/json; charset=utf-8', 'Vary': 'Origin, X-Origin, Referer', 'Content-Encoding': 'gzip', 'Server': 'scaffolding on HTTPServer2', 'X-XSS-Protection': '0', 'X-Frame-Options': 'SAMEORIGIN', 'X-Content-Type-Options': 'nosniff', 'Alt-Svc': 'h3=":443"; ma=2592000,h3-29=":443"; ma=2592000,h3-T051=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"', 'Transfer-Encoding': 'chunked'}
body: {
  "error": "invalid_grant",
  "error_description": "Malformed auth code."
}

Any advice ?

Kind regards, Juliano


Solution

  • Apologies if I'm missing your intent; it's unclear why you want to automate the flow using the OAuth Playground.

    If you're trying to automate the OAuth flow for any of Google's services, I encourage you to use Google's (Python) SDKs rather than hand-roll your own auth code.

    For example, see the OAuth flow documented here for (the) Gmail service.

    A strength of Google's APIs is that there's one for every Google service and, once you are familiar with the mechanism for one service, you can apply the principles to every service.