Here are the steps to integrate Google OAuth with FastAPI:
Go to the Google Cloud Console and create a new project.
On the left-hand menu, select "APIs & Services", then "Dashboard".
Click on "Enable APIs and Services" and search for "Google OAuth API". Click on the result and enable the API.
On the left-hand menu, select "Credentials", then "Create credentials" and select "OAuth client ID".
Select "Web application" as the application type.
Add "http://localhost:8000/callback" as the authorized redirect URI and save.
Take note of the generated client ID and client secret.
Install the google-auth
and google-auth-oauthlib
packages: pip install google-auth google-auth-oauthlib
.
In your FastAPI application, create a new endpoint for the login flow. This endpoint should redirect the user to the Google OAuth consent screen.
from fastapi import FastAPI, Request, Response
from fastapi.responses import RedirectResponse
from google.oauth2 import client
app = FastAPI()
@app.get("/login")
async def login(request: Request):
flow = client.WebAppFlow.from_client_config(
{"client_id": CLIENT_ID, "client_secret": CLIENT_SECRET, "redirect_uris": ["http://localhost:8000/callback"]},
["https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email"],
)
authorization_url, _ = flow.authorization_url(
access_type="offline", prompt="consent"
)
return RedirectResponse(url=authorization_url)
@app.get("/callback")
async def callback(request: Request, response: Response, code: str = None, error: str = None):
if error:
return {"error": error}
flow = client.WebAppFlow.from_client_config(
{"client_id": CLIENT_ID, "client_secret": CLIENT_SECRET, "redirect_uris": ["http://localhost:8000/callback"]},
["https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email"],
)
flow.fetch_token(code=code)
credentials = flow.credentials
id_info = credentials.id_token["sub"]
return {"id": id_info}
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2022-11-04 11:00:00 +0000
Seen: 18 times
Last updated: Feb 08 '22
What is the process of authentication for tokens in Firebase Cloud Messaging?
How can mutual authentication be implemented on a development server for a Django web application?
What does receiving a 401 error from Netsuite REST API imply?
What is the method to only render components on the client side in NextJS 13?
How can the server update the Firebase ID token?
How can authorized API resources be utilized with a public client in Keycloak?