Server Side Google Authentication using FastAPI and ReactJS
Last Updated :
12 Apr, 2025
FastAPI is a modern, fast, web framework for building APIs with Python, and react is a javascript library that can be used to develop single-page applications. So in this article, we are going to discuss the server-side authentication using FastAPI and Reactjs and we will also set the session.
First of all, it will be better if you create a virtual environment in python to keep our dependencies separate from other projects. For doing this install a virtual environment and activate that. You can refer to this article or read about this on the Internet.
Before proceeding further please create a project on the google cloud console. In our case, the Authorized JavaScript origin is http://localhost:3000, and the Authorized redirect URI is http://localhost:3000/auth/google/callback.
So for the authentication, we will be using google auth and receive the ID token that ID token will be transferred to the backend and then the backend will verify whether it is valid or not. If it is valid then we will set the session otherwise request will be rejected.
Let's start with the backend setup first :
- pip install fastapi: For REST interface to call commonly used functions to implement applications.
- pip install itsdangerous: Lets you use a login serializer to encrypt and decrypt the cookie token.
- pip install uvicorn: For ASGI server.
- pip install google-auth: Google authentication library for Python.
- pip install requests: For making HTTP requests in Python.
We will be using port 8000 for the backend and 3000 for the front-end part. Allowed origins should be added to avoid cors error. In our case, it is "http://localhost:3000".
Now our next step will be to create auth API endpoint for receiving the ID token. Then call the verify_oauth2_token function and pass the ID token and the clientID for verification. If the request is successful then set the session. We are adding an email id in the session cookie just for example.
Python
from typing import Optional
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from starlette.requests import Request
from starlette.middleware.sessions import SessionMiddleware
import uvicorn
from google.oauth2 import id_token
from google.auth.transport import requests
app = FastAPI()
origins = [
"http://localhost:3000",
]
app.add_middleware(SessionMiddleware ,secret_key='maihoonjiyan')
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/auth")
def authentication(request: Request,token:str):
try:
# Specify the CLIENT_ID of the app that accesses the backend:
user =id_token.verify_oauth2_token(token, requests.Request(), "116988546-2a283t6anvr0.apps.googleusercontent.com")
request.session['user'] = dict({
"email" : user["email"]
})
return user['name'] + ' Logged In successfully'
except ValueError:
return "unauthorized"
@app.get('/')
def check(request:Request):
return "hi "+ str(request.session.get('user')['email'])
if __name__ == "__main__":
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
The backend server is ready to run python filename.py, For the frontend create a react app
npx create-react-app my-app
cd my-app
npm start
Now again install an npm package npm i react-google-login and add the google login button and feed client ID. Then make a request to the backend along with the token. please add credentials:'include' otherwise cookies will not be shared with any request you make after successful authentication.
JavaScript
import GoogleLogin from 'react-google-login';
const responseGoogle = (response) => {
if (response.tokenId){
fetch('http://localhost:8000/auth?token='+ response.tokenId,{
credentials: 'include',
// To cause browsers to send a request with credentials included on both same-origin and cross-origin calls,
// add credentials: 'include' to the init object you pass to the fetch() method.
})
.then((response) => {
return response.json();
})
.then((myJson) => {
alert(myJson)
});
}
}
const temp = () =>{
fetch('http://localhost:8000',{
credentials:'include'
})
.then((response) => {
return response.json();
})
.then((myJson) => {
alert(myJson)
});
}
function App() {
return (
<div className="App">
<GoogleLogin
clientId="116988534719-0j3baq1jkp64v4ghen352a283t6anvr0.apps.googleusercontent.com"
buttonText="Google Login"
onSuccess={responseGoogle}
onFailure={responseGoogle}
cookiePolicy={'single_host_origin'}
/>
<br/>
<button onClick={temp}> Check session </button>
</div>
);
}
Here check session button is used to check whether cookies are set or not after the authentication.
Check out the full code of the entire app here.
Similar Reads
Build an Authentication System Using Django, React and Tailwind In this article, we will guide you in building an Authentication system using React and Tailwind with the Django Framework that includes features like sign up, log in, forgot password, and reset password. Weâll explore the integration of Django, React, and Tailwind CSS and go through the step-by-ste
15+ min read
OAuth Authentication with Flask - Connect to Google, Twitter, and Facebook In this article, we are going to build a flask application that will use the OAuth protocol to get user information. First, we need to understand the OAuth protocol and its procedure. What is OAuth? OAuth stands for Open Authorization and was implemented to achieve a connection between online servic
8 min read
Flask API Authentication with JSON Web Tokens Authentication is the process of verifying the identity of the user. It checks whether the user is real or not. It is used to provide access to resources only to valid users. There are two types of Authentication: Single Factor Authentication: In this only one piece of information is needed to verif
7 min read
How to Connect ReactJS with flask API ? Connecting React with Flask API allows us to create a full-stack web application with React handling the user interface at frontend and Flask serving the data in backend. Here React makes the HTTP request to interact with the flask API to perform operations with the database. ApproachTo connect Reac
4 min read
Making HTTP Requests from a FastAPI Application to an External API FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. It is designed to be easy to use, efficient, and reliable, making it a popular choice for developing RESTful APIs and web applications. Your FastAPI server may need to
4 min read
Introduction to FastAPI And Installation Introduction to FastAPIFastAPI is a modern, fast (as the name suggests), and highly performant Python web framework used for building APIs. It is built on top of standard Python-type hints and is powered by asynchronous programming using Python's "asyncio". FastAPI is known for its speed, simplicity
4 min read
FastAPI - Cookie Parameters FastAPI is a cutting-edge Python web framework that simplifies the process of building robust REST APIs. In this beginner-friendly guide, weâll walk you through the steps on how to use Cookie in FastAPI. What are Cookies?Cookies are pieces of data stored on the client browser by the server when the
4 min read
FastAPI - Header Parameters FastAPI is the fastest-growing Python API development framework, It is easy to lightweight, and user-friendly and It is based on standard Python-type hints, which makes it easier to use and understand. FastAPI supports header parameters, these are used to validate and process incoming API calls. In
4 min read
Configuring CORS in FastAPI In this article, we are going to see what is an Origin, what is CORS, and how CORS can be used to enable different origins to access and share resources. We will see why the CORS issue occurs when the frontend and backend is present in different origin and how the browser sends a request to the serv
5 min read
FastAPI Architecture FastAPI is a cutting-edge Python web framework that simplifies the process of building robust REST APIs. In this article, we will explore the fundamental aspects of architecture by delving into its core components. What is FastAPI?FastAPI is a modern, fast (high-performance), web framework for build
11 min read