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
Python Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions
Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs
Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Enumerate() in Python
enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Data Types
Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Python Introduction
Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Input and Output in Python
Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read