Skip to content

Instantly share code, notes, and snippets.

@jak010
Last active November 27, 2023 15:47
Show Gist options
  • Save jak010/e5353693155db8e2b33816ecdeaa1049 to your computer and use it in GitHub Desktop.
Save jak010/e5353693155db8e2b33816ecdeaa1049 to your computer and use it in GitHub Desktop.
google oauth id-token, access-token automation
import requests
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib import parse
client_id = ""
client_secret = ""
google_email = ""
def get_token_url():
url = "https://accounts.google.com/o/oauth2/v2/auth"
params = {
"scope": 'https://www.googleapis.com/auth/userinfo.profile',
"access_type": "offline",
"include_granted_scopes": "true",
"redirect_uri": "http://localhost:3000/api/auth/callback/google",
"client_id": client_id,
"response_type": "code",
"login_hint": google_email
}
url = url + "?" + parse.urlencode(params)
return url
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def request_access_token(self, code):
token_uri = "https://oauth2.googleapis.com/token"
r = requests.post(token_uri, data={
"client_id": client_id,
"client_secret": client_secret,
'redirect_uri': 'http://localhost:3000/api/auth/callback/google',
"grant_type": "authorization_code",
"code": parse.unquote(code)
})
return r.text
def do_GET(self):
if self.path.startswith("/api"):
query = parse.urlparse(self.path).query # 2.id-token parsing
query_params = parse.parse_qs(query) # id-token query paramas
code = query_params['code'][0] # 3. get id-token
print(code)
print(self.request_access_token(code))
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.end_headers()
httpd = HTTPServer(('0.0.0.0', 3000), SimpleHTTPRequestHandler)
print(get_token_url())
print(f'Server running on port:{3000}')
httpd.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment