How To Implement Google Auto-login With Token Validation On The Backend

0
422

To implement Google auto-login with token validation on the backend, follow these steps:


1. Get Google OAuth 2.0 Credentials

  • Go to the Google Cloud Console.
  • Create a new project (if not already created).
  • Navigate to APIs & Services > Credentials.
  • Create OAuth 2.0 credentials (Client ID and Client Secret).
  • Set up the Authorized Redirect URIs.

2. Frontend: Get Google ID Token

Use the Google Identity Services (GIS) Library to log in users and retrieve the ID token.

Example: Using Google Sign-In Button (JavaScript)

<script src="https://accounts.google.com/gsi/client" async defer></script>
<div id="g_id_onload"
     data-client_id="YOUR_GOOGLE_CLIENT_ID"
     data-context="signin"
     data-ux_mode="popup"
     data-callback="handleCredentialResponse"
     data-auto_prompt="true">
</div>
<script>
  function handleCredentialResponse(response) {
    fetch('/api/auth/google-login', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ token: response.credential })
    })
    .then(res => res.json())
    .then(data => console.log(data));
  }
</script>

This automatically logs in users and sends the Google ID Token to the backend.


3. Backend: Validate Google Token (Node.js & Express Example)

Use Google's oauth2 package to verify the token.

Install Required Packages

npm install express cors google-auth-library jsonwebtoken

Backend Code (Node.js)

const express = require('express');
const cors = require('cors');
const { OAuth2Client } = require('google-auth-library');
const jwt = require('jsonwebtoken');

const app = express();
app.use(express.json());
app.use(cors());

const GOOGLE_CLIENT_ID = "YOUR_GOOGLE_CLIENT_ID";
const JWT_SECRET = "your_jwt_secret"; // Change this for production

const client = new OAuth2Client(GOOGLE_CLIENT_ID);

// Verify Google ID Token
async function verifyGoogleToken(token) {
    const ticket = await client.verifyIdToken({
        idToken: token,
        audience: GOOGLE_CLIENT_ID,
    });
    return ticket.getPayload();
}

app.post('/api/auth/google-login', async (req, res) => {
    const { token } = req.body;

    try {
        const googleUser = await verifyGoogleToken(token);
        const { sub, email, name, picture } = googleUser;

        // Generate JWT Token
        const userToken = jwt.sign({ sub, email, name, picture }, JWT_SECRET, { expiresIn: '1h' });

        res.json({ success: true, token: userToken, user: { email, name, picture } });
    } catch (error) {
        res.status(401).json({ success: false, message: "Invalid token" });
    }
});

app.listen(5000, () => console.log("Server running on port 5000"));

4. Verify JWT on Protected Routes

Once the Google token is validated, you can use JWT for authentication.

Middleware for Protected Routes

function authenticateToken(req, res, next) {
    const authHeader = req.headers.authorization;
    const token = authHeader && authHeader.split(' ')[1];

    if (!token) return res.sendStatus(401);

    jwt.verify(token, JWT_SECRET, (err, user) => {
        if (err) return res.sendStatus(403);
        req.user = user;
        next();
    });
}

// Example Protected Route
app.get('/api/protected', authenticateToken, (req, res) => {
    res.json({ message: "This is a protected route", user: req.user });
});

5. Testing

  1. Start the backend:
    node server.js
    
  2. Implement the frontend Google login.
  3. The frontend sends the ID token to the backend.
  4. The backend verifies the token, creates a JWT, and returns it.
  5. The frontend stores the JWT and uses it for API authentication.

Key Takeaways

  • Auto Login: The Google Sign-In button automatically signs in returning users.
  • Token Validation: Google ID tokens are verified on the backend.
  • JWT Usage: After validation, a JWT is issued for future authentication.
  • Secure Routes: Middleware protects routes using JWT.