1K Views
Backend Validation For Facebook Auto-login
For backend validation of the Facebook auto-login, you need to:
- Get the Facebook Access Token from the frontend.
- Send the Token to Your Backend.
- Validate the Token with Facebook's API.
- Fetch the User's Profile Data securely.
Backend Implementation (Node.js with Express & Axios)
1. Install Dependencies
npm init -y
npm install express axios dotenv cors
2. Create Backend (server.js)
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}`);
});
3. Setup Environment Variables (.env)
FACEBOOK_APP_ID=your_facebook_app_id
FACEBOOK_APP_SECRET=your_facebook_app_secret
PORT=5000
Frontend - Send Token to Backend
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'});
}
How This Works
- Frontend retrieves the Facebook
accessTokenafter login. - Sends
accessTokento the backend for validation. - Backend validates the token using Facebook's Debug API.
- If valid, backend fetches user data and returns it securely.
- Frontend displays the user details.
Security Best Practices
- Never trust client-side authentication alone—always validate tokens on the backend.
- Use HTTPS to avoid MITM attacks.
- Store tokens securely if maintaining sessions (e.g., JWTs).
- Limit API scopes to only required permissions (like
emailandpublic_profile).
Now your website supports secure Facebook auto-login with backend verification! Need additional help with token storage (JWT, sessions)?