Friday, November 15, 2024
Google search engine
HomeLanguagesServer Side Google Authentication using FastAPI and ReactJS

Server Side Google Authentication using FastAPI and ReactJS

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 :

  1. pip install fastapi: For REST interface to call commonly used functions to implement applications.
  2. pip install itsdangerous: Lets you use a login serializer to encrypt and decrypt the cookie token.
  3. pip install uvicorn: For ASGI server.
  4. pip install google-auth: Google authentication library for Python.
  5. 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 = [
]
  
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.

RELATED ARTICLES

Most Popular

Recent Comments