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
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
Authentication using Python requests
Authentication refers to giving a user permissions to access a particular resource. Since, everyone can't be allowed to access data from every URL, one would require authentication primarily. To achieve this authentication, typically one provides authentication data through Authorization header or a
2 min read
Authentication and Authorization with FastAPI
FastAPI is the modern, high-performance web framework for building the APIs with Python 3.6+ based on the standard type hints. FastAPI is gaining popularity due to its ease of use, robustness and ability to create the APIs quickly. Authentication and authorization are crucial components of any web a
6 min read
Two-Factor Authentication using Google Authenticator in Python
Two Factor Authentication or 2FA is an advanced method of user authentication and a subset of multi-factor authentication mechanisms. 2FA enhances the security of its user accounts by adding another layer of authenticity challenge after traditional passwords are used in single-factor authentication.
3 min read
Testing FastAPI Application
The web framework in Python that is used for creating modern and fast APIs is called FastAPI. Once we have created the FastAPI, there is a need to test if the API is working fine or not according to the requirements. In this article, we will discuss the various ways to test the FastAPI application.
3 min read
Run the fast-api server using Pycharm
FastAPI is a Python web framework that makes it easy to build APIs quickly and efficiently. Returning an image is a common requirement in web development, and FastAPI makes it straightforward to do. another famous framework for doing the same is Flask, which is also Python-based. Pre-requisitePyChar
3 min read
Creating First REST API with FastAPI
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 to create your very first REST API using FastAPI. By the end, you'll have a solid foundation for building and deploying APIs with
5 min read
Django+React Full Stack Development Setup using Dact
When we work on a project having Django as our Back-end and having a powerful front-end using React, the development setup takes a significant amount of time to setup - configuring Babel, Webpack, URLs, views, etc. We used to set up this earlier to get started with ReactJS before npx create-react-ap
2 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
Return an Image in FastAPI
FastAPI is a Python web framework that makes it easy to build APIs quickly and efficiently. Returning an image is a common requirement in web development, and FastAPI makes it straightforward to do. another famous framework for doing the same is Flask, which is also Python-based. In this article, we
4 min read