Introduction to Backend Development
Web Development |
2025-01-17 16:06:49
For backend validation of the Facebook auto-login, you need to:
npm init -y
npm install express axios dotenv cors
require('dotenv').config();
const express = require('express');
const axios = require('axios');
const cors = require('cors');
const app = express();
app.use(express.json());
app.use(cors());
const FACEBOOK_APP_ID = process.env.FACEBOOK_APP_ID;
const FACEBOOK_APP_SECRET = process.env.FACEBOOK_APP_SECRET;
// Route to verify Facebook Access Token
app.post('/auth/facebook', async (req, res) => {
const { accessToken } = req.body;
if (!accessToken) {
return res.status(400).json({ error: 'Access Token is required' });
}
try {
// Validate the token with Facebook
const fbVerifyUrl = `https://graph.facebook.com/debug_token?input_token=${accessToken}&access_token=${FACEBOOK_APP_ID}|${FACEBOOK_APP_SECRET}`;
const { data: verification } = await axios.get(fbVerifyUrl);
if (!verification.data.is_valid) {
return res.status(401).json({ error: 'Invalid Facebook Token' });
}
// Get user details
const userUrl = `https://graph.facebook.com/me?fields=id,name,email&access_token=${accessToken}`;
const { data: user } = await axios.get(userUrl);
res.json({ message: 'Login successful', user });
} catch (error) {
res.status(500).json({ error: 'Facebook Authentication Failed', details: error.message });
}
});
// Start server
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
.env
)FACEBOOK_APP_ID=your_facebook_app_id
FACEBOOK_APP_SECRET=your_facebook_app_secret
PORT=5000
Modify the existing JavaScript to send the token to the backend.
function loginWithFacebook() {
FB.login(function(response) {
if (response.authResponse) {
const accessToken = response.authResponse.accessToken;
fetch('http://localhost:5000/auth/facebook', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ accessToken })
})
.then(response => response.json())
.then(data => {
if (data.user) {
document.getElementById('user-info').innerHTML =
`Welcome, ${data.user.name} (${data.user.email})`;
} else {
console.error('Login failed:', data.error);
}
})
.catch(err => console.error('Error:', err));
}
}, {scope: 'email'});
}
accessToken
after login.accessToken
to the backend for validation.email
and public_profile
).Now your website supports secure Facebook auto-login with backend verification! Need additional help with token storage (JWT, sessions)?