Instagram
youtube
Facebook
Twitter

Facebook Authentication

Facebook Authentication

  • In this tutorial, we will code facebook authentication using ExpressJs and passport.js
  • Passport. js is a popular Express middleware specifically created to facilitate the login process. It is flexible, trusted by many organizations worldwide, and easy to integrate into your ExpressJS code.
  • Install passport in the project by the following command:
npm install passport passport-local

To start, Firstly register on your Facebook app and begin with the following steps:

  • Select app type and click NEXT

  • Add basic details of the App, App name, and email, and click on create an app.

  • After creating an app, click on setting present on the left side and then select basic, and do the following change done in below image and we will get AppID and App Secret.

  • Scroll Down and click on add platform and paste the local host URL and click on save changes.

Now let's move to the code part. here is an application file structure

  • For the frontend part, views/header.ejs, views/footer.ejs, views/home.ejs.

In header.ejs

<!DOCTYPE html>
<html lang="en">
<head>
    <title>ExpressJS: login with Facebook</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <link rel="stylesheet" href="/public/css/style.css" type="text/css" media="screen">
</head>
<body>
<main id="site">

In home.ejs

<%- include('header') %>

<section class="jumbotron container mt-5">
<% if (!user) { %>
	<h1>Welcome!</h1> 
	<p class="mt-5"><a href="/login/facebook" class="loginBtn loginBtn--facebook">Login with Facebook</a></p>
<% } else { %>
	<h1>Hello, <%= user.displayName %>.</h1>
	<p class="mt-5"><a href="/logout" class="btn btn-primary">Logout</a></p>
<% } %>
</section>

<%- include('footer') %>
  • Now for routes In routes/index.js
'use strict';

const express = require('express');
const passport = require('passport');
const router = express.Router();

router.get('/', (req, res, next) => {
    const { user } = req;
    res.render('home', { user });
});

router.get('/login/facebook', passport.authenticate('facebook'));

router.get('/logout', (req, res, next) => {
  req.logout();
  res.redirect('/');
});

router.get('/return', 
  passport.authenticate('facebook', { failureRedirect: '/' }),
  (req, res, next) => {
    res.redirect('/');
});

module.exports = router;
  • Lastly, for the server there we use passport and express to authenticate
'use strict';

require('dotenv').config();

const path = require('path');
const express = require('express');
const passport = require('passport');
const { Strategy } = require('passport-facebook');
const { FACEBOOK_CLIENT_ID, FACEBOOK_CLIENT_SECRET, SESSION_SECRET } =  process.env;
const app = express();
const routes = require('./routes');

passport.use(new Strategy({
    clientID: FACEBOOK_CLIENT_ID,
    clientSecret: FACEBOOK_CLIENT_SECRET,
    callbackURL: '/return'
  },
  (accessToken, refreshToken, profile, cb) => {
    return cb(null, profile);
}));

passport.serializeUser((user, cb) => {
  cb(null, user);
});

passport.deserializeUser((obj, cb) => {
  cb(null, obj);
});

app.set('view engine', 'ejs');

app.use('/public', express.static(path.join(__dirname, 'public')));

app.use(require('express-session')({ secret: SESSION_SECRET, resave: true, saveUninitialized: true }));

app.use(passport.initialize());
app.use(passport.session());
app.use('/', routes);



app.listen(3000,()=>{
  console.log('Express server started at port:3000')
});
  • clientID, Clientsecret, and callback URL are mentioned in .env file
FACEBOOK_CLIENT_ID=YOUR_CLIENT_ID
FACEBOOK_CLIENT_SECRET=YOUR_CLIENT_SECRET
SESSION_SECRET=YOUR_SESSION_SECRET

Now start the server by command and the server will start at port 3000: http://localhost:3000/

npm start

facebook login success

Thus, Facebook authentication can be added to any website or app using Expressjs and passport.js.