Skip to main content

Google OAuth

·269 words·2 mins
Themes Guide - This article is part of a series.
Part : This Article

Overview #

  1. Links
https://github.com/rawalpurvi/sign_in_with_google_for_web/tree/main
https://developers.google.com/identity/gsi/web/guides/get-google-api-clientid
https://medium.com/@purvirawal.work/sign-in-with-google-for-web-4f03a693b14f
https://developers.google.com/identity/gsi/web/guides/display-button
https://testdriven.io/blog/moving-from-flask-to-fastapi/
https://stackoverflow.com/questions/68556923/how-to-send-a-starlette-formdata-data-structure-to-a-fastapi-endpoint-via-python
https://stackoverflow.com/questions/69641363/how-to-run-fastapi-app-on-multiple-ports
https://medium.com/hippo-engineering-blog/securing-a-fastapi-route-using-jwt-token-step-by-step-f4c03d96a8ea
https://stackoverflow.com/questions/74917863/fastapi-unable-to-get-auth-token-from-middlewares-request-object
https://www.starlette.io/requests/#query-parameters
https://developers.google.com/identity/gsi/web/guides/overview
https://learnpython.com/blog/python-requirements-file/
https://flask.palletsprojects.com/en/2.3.x/quickstart/
  1. HTML
<html>
<body>
    <script src="https://accounts.google.com/gsi/client" async defer></script>
    <div id="g_id_onload" data-client_id="{{ GOOGLE_CLIENT_ID }}" data-login_uri="http://localhost:5000/login"
        data-auto_prompt="false">
    </div>
    <div class="g_id_signin" data-type="standard" data-size="large" data-theme="outline" data-text="sign_in_with"
        data-shape="rectangular" data-logo_alignment="left">
    </div>
</body>
</html>
  1. App.py
# Google library for verify the token
from google.oauth2 import id_token
from google.auth.transport import requests

# Third-party libraries
from flask import Flask, render_template, request, jsonify

app = Flask(__name__)
GOOGLE_CLIENT_ID = '391834189398-m50g0l1n1driobkvs1gminlh9httc4qr.apps.googleusercontent.com'

'''
Login page get Google Signin Button.
'''


@app.route('/')
def index():
    # render login page
    return render_template("index.html", GOOGLE_CLIENT_ID=GOOGLE_CLIENT_ID)


'''
After user login set all values to display.
'''


@app.route('/login', methods=['POST', 'GET'])
def login():
    # Get google credential
    token = request.form.get("credential")
    print(f'hello {token}')
    if not token:
        return "Not logged in"
    else:
        # Verify Google Response Token
        try:
            # Specify the CLIENT_ID of the app that accesses the backend:
            user_info = id_token.verify_oauth2_token(token, requests.Request(), GOOGLE_CLIENT_ID)
            print(user_info)
            jwt_token_info = jsonify({"data": user_info})
            return f"log in successful {jwt_token_info}"
        except ValueError:
            # Invalid token
            pass


if __name__ == "__main__":
    app.run(port=5000, debug=True)
  1. Requirements.txt
google-auth
flask
python-multipart
fastapi
requests
  1. FastAPI
from google.oauth2 import id_token
from google.auth.transport import requests


from fastapi import FastAPI, Request
from fastapi.staticfiles import StaticFiles

app = FastAPI()
app.mount("/login", app)
app.mount("/ui", StaticFiles(directory="ui", html=True), name="ui")
GOOGLE_CLIENT_ID = '677925369817-os3rv3oblmlgrn9vaqr69mpf3e3jff00.apps.googleusercontent.com'


@app.post("/login")
async def login(request: Request):
    form = await request.form()
    # Get google credential
    token = form["credential"]
    if not token:
        return "Not logged in"
    else:
        # Verify Google Response Token
        try:
            # Specify the CLIENT_ID of the app that accesses the backend:
            user_info = id_token.verify_oauth2_token(token, requests.Request(), GOOGLE_CLIENT_ID)
            print(user_info)
            # jwt_token_info = jsonify({"data": user_info})
            return "log in successful"
        except ValueError:
            # Invalid token
            pass
  1. premium access
https://buy.stripe.com/4gw3eedMW8iH9LqdQQ
Themes Guide - This article is part of a series.
Part : This Article