raphael
b676ee1a71
- basic login button on website frontend - index.html hosting using python - posting google oauth token from javascript on client side - passing token id to python hoster - verifying token, and returning a string to client
80 lines
2.5 KiB
Python
80 lines
2.5 KiB
Python
from google.oauth2 import id_token
|
|
from google.auth.transport import requests
|
|
|
|
from http.server import HTTPServer, SimpleHTTPRequestHandler, BaseHTTPRequestHandler
|
|
import socketserver
|
|
import logging
|
|
import json
|
|
|
|
Handler = SimpleHTTPRequestHandler
|
|
|
|
class S(BaseHTTPRequestHandler):
|
|
def _set_headers(self):
|
|
self.send_response(200)
|
|
self.send_header('Content-type', 'text/html')
|
|
self.end_headers()
|
|
|
|
def do_GET(self):
|
|
self._set_headers()
|
|
f = open("index.html", "r")
|
|
self.wfile.write(f.read().encode('utf-8'))
|
|
|
|
def do_HEAD(self):
|
|
self._set_headers()
|
|
|
|
def do_POST(self):
|
|
self._set_headers()
|
|
print("in post method")
|
|
self.data_string = self.rfile.read(int(self.headers['Content-Length']))
|
|
print('checking client id')
|
|
checkClientId(self.data_string)
|
|
self.send_response(200)
|
|
self.end_headers()
|
|
self.wfile.write("Hello".encode('utf-8'))
|
|
return
|
|
|
|
def run(server_class=HTTPServer, handler_class=S, port=1234):
|
|
logging.basicConfig(level=logging.INFO)
|
|
server_address = ('', port)
|
|
with socketserver.TCPServer(("", port), handler_class) as httpd:
|
|
print("serving at port", port)
|
|
httpd.serve_forever()
|
|
|
|
|
|
# (Receive token by HTTPS POST)
|
|
def checkClientId(token):
|
|
try:
|
|
|
|
with open('client_secret.json', 'r') as json_file:
|
|
clientSecret = json.load(json_file)
|
|
CLIENT_ID = clientSecret["web"]["client_id"]
|
|
# Specify the CLIENT_ID of the app that accesses the backend:
|
|
idinfo = id_token.verify_oauth2_token(token, requests.Request(), CLIENT_ID)
|
|
|
|
# Or, if multiple clients access the backend server:
|
|
# idinfo = id_token.verify_oauth2_token(token, requests.Request())
|
|
# if idinfo['aud'] not in [CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]:
|
|
# raise ValueError('Could not verify audience.')
|
|
|
|
if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']:
|
|
raise ValueError('Wrong issuer.')
|
|
|
|
# If auth request is from a G Suite domain:
|
|
# if idinfo['hd'] != GSUITE_DOMAIN_NAME:
|
|
# raise ValueError('Wrong hosted domain.')
|
|
|
|
# ID token is valid. Get the user's Google Account ID from the decoded token.
|
|
userid = idinfo['sub']
|
|
print(f"valid user id: {userid}")
|
|
except ValueError:
|
|
# ID token is invalid
|
|
print('invalid token')
|
|
pass
|
|
|
|
if __name__ == '__main__':
|
|
from sys import argv
|
|
|
|
if len(argv) == 2:
|
|
run(port=int(argv[1]))
|
|
else:
|
|
run() |