শনিবার, ১৯ আগস্ট, ২০২৩

Implementing Google Social Authentication in a FastAPI backend with a React frontend involves several steps.

Implementing Google Social Authentication in a FastAPI backend with a React frontend involves several steps. In this example, I'll walk you through the process, starting with the backend and then the frontend. Please note that this example assumes you have a basic understanding of FastAPI, React, and JavaScript.

**Backend (FastAPI):**

1. **Set up a FastAPI Project:**

   Make sure you have FastAPI installed. You can create a FastAPI project using a tool like `cookiecutter` or manually create one.

2. **Install Required Libraries:**

   Install the necessary libraries for authentication:
   
   ```bash
   pip install fastapi uvicorn python-oauthlib httpx authlib
   ```

3. **Create a Google OAuth2 App:**

   Go to the Google Developer Console (https://console.developers.google.com/), create a new project, and set up OAuth2 credentials. Make sure to set the redirect URI to match your FastAPI server's endpoint (e.g., `http://localhost:8000/login/callback` for local development).

4. **Configure OAuth2 in FastAPI:**

   Create a file (e.g., `auth.py`) to handle OAuth2 authentication:

   ```python
   from fastapi import FastAPI, Depends, HTTPException
   from authlib.integrations.starlette_client import OAuth
   from fastapi.security.oauth2 import OAuth2PasswordBearer
   from authlib.integrations.httpx_client import AsyncOAuth2Client
   from fastapi.middleware.cors import CORSMiddleware

   app = FastAPI()

   origins = ["http://localhost:3000"]  # Update with your React app's URL.

   app.add_middleware(
       CORSMiddleware,
       allow_origins=origins,
       allow_credentials=True,
       allow_methods=["*"],
       allow_headers=["*"],
   )

   oauth = OAuth(app, AsyncOAuth2Client)

   oauth.register(
       name="google",
       client_id="YOUR_GOOGLE_CLIENT_ID",
       client_secret="YOUR_GOOGLE_CLIENT_SECRET",
       authorize_url="https://accounts.google.com/o/oauth2/auth",
       authorize_params=None,
       authorize_extra_params=None,
       token_url="https://accounts.google.com/o/oauth2/token",
   )
   ```

   Make sure to replace `"YOUR_GOOGLE_CLIENT_ID"` and `"YOUR_GOOGLE_CLIENT_SECRET"` with your actual Google OAuth credentials.

5. **Create Authentication Routes:**

   Create routes for OAuth2 authentication and callback:

   ```python
   @app.get("/login/google")
   async def login_with_google():
       redirect_uri = url_for("auth", _external=True)
       return await oauth.google.authorize_redirect(redirect_uri)

   @app.get("/login/callback")
   async def auth():
       token = await oauth.google.authorize_access_token()
       user = await oauth.google.parse_id_token(token)
       # Handle user data (e.g., store in a database)
       return {"user": user}
   ```

6. **Run the FastAPI Server:**

   Start the FastAPI server using Uvicorn:

   ```bash
   uvicorn main:app --host 0.0.0.0 --port 8000 --reload
   ```

**Frontend (React):**

1. **Create a React App:**

   Set up a React app using Create React App or your preferred method.

2. **Install Required Libraries:**

   Install the necessary libraries for handling OAuth2 in your React app:

   ```bash
   npm install axios react-oauth/google
   ```

3. **Implement Google Login Button:**

   In your React component, create a button to initiate the Google OAuth2 login:

   ```jsx
   import React from "react";
   import { GoogleLoginButton } from "react-oauth/google";

   const App = () => {
     const handleGoogleLogin = () => {
       // Redirect to your FastAPI login route
       window.location.href = "http://localhost:8000/login/google";
     };

     return (
       <div>
         <h1>My App</h1>
         <GoogleLoginButton onClick={handleGoogleLogin} />
       </div>
     );
   };

   export default App;
   ```

4. **Handle Redirect from FastAPI:**

   When the user returns from the FastAPI server after Google authentication, you can extract the user data from the URL or use an authentication state management library like Redux or React Context to handle the user data.

That's it! This example demonstrates how to implement Google Social Authentication in a FastAPI backend with a React frontend. Make sure to adjust the URLs, credentials, and error handling according to your specific requirements and production environment.


In the example I provided earlier, the first URL that can be hit is the login URL for Google OAuth2 authentication. This URL is defined in your FastAPI backend as follows:

```python
@app.get("/login/google")
async def login_with_google():
   redirect_uri = url_for("auth", _external=True)
   return await oauth.google.authorize_redirect(redirect_uri)
```

In this code, when a user navigates to the `/login/google` route in your FastAPI application, it triggers the `login_with_google` function. Inside this function, it prepares a redirect URL to Google's OAuth2 authorization page and then redirects the user to that URL.

The Google OAuth2 authorization URL is constructed based on the OAuth configuration you provided when registering your OAuth2 client with Google. This URL is where users will log in with their Google accounts and grant permission to your application.

Once users complete the Google login and authorization process, they will be redirected back to your FastAPI application's callback URL, which is defined as `/login/callback` in the example:

```python
@app.get("/login/callback")
async def auth():
   token = await oauth.google.authorize_access_token()
   user = await oauth.google.parse_id_token(token)
   # Handle user data (e.g., store in a database)
   return {"user": user}
```

In this `/login/callback` route, your FastAPI application receives the authorization code from Google, exchanges it for an access token, and retrieves user information.

So, to initiate the Google OAuth2 authentication process, you would navigate to `http://localhost:8000/login/google` (assuming you are running your FastAPI server locally on port 8000). This URL triggers the login process with Google, and upon successful authentication, users are redirected back to your FastAPI application's `/login/callback` route to complete the authentication flow.