How to Create a slider in HTML
HTML |
2025-02-13 19:01:03
To implement Google auto-login with token validation on the backend, follow these steps:
Use the Google Identity Services (GIS) Library to log in users and retrieve the ID token.
<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.
Use Google's oauth2
package to verify the token.
npm install express cors google-auth-library jsonwebtoken
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"));
Once the Google token is validated, you can use JWT for authentication.
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 });
});
node server.js