How To Implement Google Auto-login With Token Validation On The Backend
Posted 2025-02-16 17:25:12
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
- Start the backend:
node server.js
- Implement the frontend Google login.
- The frontend sends the ID token to the backend.
- The backend verifies the token, creates a JWT, and returns it.
- 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.
Search
Sellect from all Categories bellow ⇓
- Artificial Intelligence (AI)
- Cybersecurity
- Blockchain & Cryptocurrencies
- Internet of Things
- Cloud Computing
- Big Data & Analytics
- Virtual Reality
- 5G & Future Connectivity
- Robotics & Automation
- Software Development & Programming
- Tech Hardware & Devices
- Tech in Healthcare
- Tech in Business
- Gaming Technologies
- Tech in Education
- Machine Learning (ML)
- Blogging
- Affiliate Marketing
- Make Money
- Digital Marketing
- Product Review
- Social Media
- Excel
- Graphics design
- Freelancing/Consulting
- FinTech (Financial Technology)
- E-commerce and Digital Marketing
- Business
- Sport
- Self Development
- Tips to Success
- Video Editing
- Photo Editing
- Website Promotion
- YouTube
- Lifestyle
- Health
- Computer
- Phone
- Music
- Accounting
- Causes
- Networking
Read More
How to Create a slider using JavaScript
Creating a slider using JavaScript involves...
How to Create a slider in HTML
Creating a slider in HTML involves using the...
how set navigation bar text color in android studio project
To set the text color for the navigation bar in...
Step By Step On How To Become A Successful Blogger
Becoming a...
Why Your Newport Business Deserves the Best SEO Agency
When you picture Newport, you might think of...