Facebook and Google Authentication with Node.js and Doppler
Tags: security, javascript
Published: 2021-09-28 07:53:41

## Summary

Facebook and Google login is widely used as an authentication module in our modern web application. There are API keys assigned to every application created using these platforms.
Managing these secrets in our application can be a nightmare when building large-scale applications that require a lot of secret keys.
With Doppler, you don't have to worry about the security and management of your API secret keys.
In this tutorial, we will learn how to create a user authentication in Node.js using Facebook and Google login, manage and secure our API secrets with Doppler.

## Goals

In this tutorial, we will authenticate users using Facebook, and Google authentication. We will manage and secure our API secrets with Doppler.
We will look at how to create a Doppler project, Facebook app, and google app. 

## Introduction

Doppler has significantly changed and increased the productivity of our applications since its release. No need to subject our secrets to vulnerabilities by storing them in a **.env** file located in our project directory. Over time, I have had to make the mistake of hosting my applications alongside my **.env**  on Github. But thanks to Doppler, all that is a thing of the past. 
Doppler has a CLI tool that runs on every operating system, to enable you to configure your applications easily, giving you access to your secrets from your development, staging to your production environment.

## Setting up Doppler

To manage your secrets using Doppler, you need to create a Doppler account. To get started, go to the  [Doppler](https://www.doppler.com/) official website and create an account for free. Sign up with your full name, email, and password. After creating an account, Doppler will need a confirmation on your email. So go to your Gmail, and confirm your email address.
Next, create a workspace for your project. For this tutorial, we’ll call our workspace `authWithDoppler`.   After creating a workspace, Doppler provides you with an example project to get started. 
Next, you need to install the Doppler CLI to access your secrets in your development environment. Check out the Doppler [documentation](https://docs.doppler.com/docs/cli) for the installation guide on your operating system. On Ubuntu, below are the installation commands.


    # Install pre-reqs
    sudo apt-get update && sudo apt-get install -y apt-transport-https ca-certificates curl gnupg
    
    # Add Doppler's GPG key
    curl -sLf --retry 3 --tlsv1.2 --proto "=https" 'https://packages.doppler.com/public/cli/gpg.DE2A7741A397C129.key' | sudo apt-key add -
    
    # Add Doppler's apt repo
    echo "deb https://packages.doppler.com/public/cli/deb/debian any-version main" | sudo tee /etc/apt/sources.list.d/doppler-cli.list
    
    # Fetch and install latest doppler cli
    sudo apt-get update && sudo apt-get install doppler

Next, verify the Doppler CLI is installed by checking its version with the command below:


    doppler --version

If everything went well, you should see the version printed on your terminal.
Finally, Login into your Doppler account from the Doppler CLI with the command below:


    doppler login

You’ll be asked for confirmation to open the authorization page on your browser. Type **Y** and hit the **Enter** key. Doppler will open the authorization page in your browser, sign in with your account details. Then proceed to your terminal, copy and paste the auth code on the auth form in your browser.

![](https://lh3.googleusercontent.com/pwQQ1uuR3VMgKGHsUFn69rIorLOB3ZjfAYCEa9r7hXyq2IMqWbE8oNMjITawQbseoCb28nWMZiIuvYlN23Tc9IGRu_vzv6bQRPvzC_FyqquwajLrruaBC4JR09lFX2q-6NMrofeq=s0)


If everything went well, you see a welcome message on your terminal. 

## Creating a Doppler Project

We will be creating a Doppler project for our application. To get started, go back to the Doppler Dashboard on your browser, click on the plus icon to create a new project. For this tutorial, we will call it `authwithdoppler`, add a little description if you want, but that’s optional.

![](https://lh6.googleusercontent.com/auJBErHbdIiDK078kNkYbThDmNZ2CifCM5BPdtTGBCip1V7EeOguPxeW82P0jOWOozd23bIY7b7zO1sA71CjHevd_PQRkmZthHk1ai-hu06-yMU16cl2lVzMdL9UnemF70M8JFXV=s0)



Doppler runs on three environments, which are development, staging, and production environments. We will cover the demonstration in a development environment. Check out the Doppler [documentation](https://docs.doppler.com/docs/enclave-installation) to know how docker works in other environments. 

## Creating a Facebook App

At this point, our Doppler is ready for our project secrets. To authenticate users using Facebook authentication in your application, you need to get your application registered on Facebook. So go to [Facebook Developers](https://developers.facebook.com/) and create an App for your project. Then select **Consumer** depending on your application use case.


![](https://lh4.googleusercontent.com/RuitT2w5pw-lgLWOlfJlaQTj8yAKY9vhjZDfXjHHDv6pkfIS31UYgSVPkbFmGkfMhJX0WHUyXDClgQ6Bu1TfVn5APTe8-7ZoKDrlIume8XTVco8d3rLFau3w0m3m9x_IORP0Gus4=s0)


Next, add your application details, add a display name. For this tutorial, we'll call it `authWithDoppler`, enter your email address, and hit the **Create App** button.

![](https://lh6.googleusercontent.com/aQ8IndAe0-N73niWP21ubChjE63cRKGjvm0tLwaVQRyO-bT4KqPrWhRdvbxI-L3ZtJH0SF1R5tHgfWpQX9-CCn7nZ2biP3Q7rioq03dBB4ODHKK-Ldj-GTrni2ASTBntgIWJf9kZ=s0)


Next, add products to the App. Since you are handling user authentication, you’ll be setting up a Facebook Login product. So click the **set up** on the Facebook Login tab. Then choose a website as your platform. 

![](https://lh6.googleusercontent.com/JTs4j1M7Uf3Vqkyx08awaNuH0dLx-cvIdFvzU6QN-iJcrpAJ0TqIWtauv1nUFNVBDzGzUfa2rW82V2dR86S1i5iHZuwxV6TpAQZRRD-eJtynmQyjFZPkvoTQPKNR4jZrCIYAxy75=s0)



Next, you'll be asked for the details of your website. If you are testing the application on localhost, then add your host address, save and continue.

![](https://lh5.googleusercontent.com/yMy-lmXs1GDcclcQG_oGnU1UQQ0cAos4qkHUYxJorqQoYGKkiilI8_dbiVKigCvLavnx4Nep5tvP0OF_Ozk20a38SFioJk1_2fm-zvghjCYwm7QYpnw1zQx05FpvE3mpNx883UTr=s0)


At this point, your Facebook app is ready. Now click on **Settings > Basic** to see your App secrets. Leave it open for now while we create a Google App.

## Creating a Google App

Creating a Google App is a straightforward process. To get started, you need to get Google credentials for your application. So go to [Google Developers Console](https://console.developers.google.com/) and create an App for your project. On the Google developers dashboard, create a new project for your application, choose a name for the project. For this tutorial, we will call it `authWithDoppler`.

![](https://lh4.googleusercontent.com/GnWDD6CKUebkAKgntZAyfjjQA4yhqa3U2ftrio7F-UJK8f5F02F7QMW12sdkxsdFydbrnORy15NhAoHiuTAZF6eRQh_p5a6vJC1xr8x_RySkooBVpBxlpTu5zlIxPrjoehF5RgKL=s0)



Next, configure your OAuth consent screen, which provides you with OAuth client ID. Then choose how you want to configure and register your app. Choose external since you are using it to authenticate your app users.

![](https://lh6.googleusercontent.com/MuIFKemN3sAWEDk7IInPH7cZZbB0aDEjVBab7yjI6mgYTaN1Rs_1TzRH7QiPH8XpnoAa0AkHbjoOMaVTw0Wiwah5984tY9zIgUgcFLuck20G-wdkC0ZZYWLMdb_MLPV-pUtTeVKz=s0)


Next, fill in the information of your application, give it the name `authWithDoppler`. Provide your email address, and your app logo.

![](https://lh5.googleusercontent.com/eOTiCIWi2RiUx5hamG8mVONqeq6XH0bkx24PQwdNn-iIUrCMPIyhFk84_mbtthV0obWw58daOTHSfRP_pddt8d60UXqppMXy6poJ6Z_YcTVq2_9dIG0tW-U8qIV_ux23INuffXQW=s0)


Now, create your App credentials. On the credentials page, create an OAuth client ID credential for your App.

![](https://lh5.googleusercontent.com/Tw7vhWcwa9GQp-kcMUzn4oGWyIrZHSB5trUQ72PtTJyuYAWffzvNljpPoWz0KFW2DdcDxhwNqDWsUn_9oOiI-D5yLIqiEUZfIvPRVC71_HKrRT6ax4KBlS88F4gvVPrMRcjsnlDW=s0)


Then, select web application as your application type. Add this line as the `https://localhost:4000` as the **authorized javascript origins**, and `http://localhost:4000/auth/google/callback` as the **authorized redirect URLs**.
After creating the App, Google will pop up a modal containing your App credentials, still leave it open while we move back to our Doppler dashboard.


## Save Our App Secret on Doppler

Our aim of using Doppler is to secure our application secrets by replacing the **.env** file. So instead of saving all our secrets in a .env file, we will save them on Doppler. To get started, 
select the **authwithdoppler** project we created, then click on the **dev** tab to save our secrets in a development environment.
Next, save your application secrets in the Doppler secret tab. Go back to your Facebook **Settings > Basic**, copy your App ID and App Secret, and save them on Doppler.


![](https://lh3.googleusercontent.com/2Q9kg-kPY5_TeCAr6W1qWFer7Zgf8qXVtXAwyy4hW9bAI419cWppa6QWABPi-p41Sqjznj__AOdKFyMys_NrLMNPF6-tifWy_aFMKSi81UBQKiKRtDtlloRKyiReB5HH19Q-tunx=s0)


Also, go back to your Google credentials page, copy your client ID and Client Secret and save them on Doppler.

![](https://lh6.googleusercontent.com/reP1_QQrQrFtPJSkm5eAx2o8bHitiYhuPExDslJKeZ6HP5HcqAF5fLWamf1ECOOFdJvb_EgFPwasrLrtEse_aJy-d_cqcpY1Ojn9aiEXTJwkQf8HEdJa0S07yJLfxEiCx_ZFmYId=s0)


Then click on the save button to save the secrets. At this point, our application secrets are saved on Doppler.

## Setting our Node.js Server

We have successfully created a Google and a Facebook App for our project. We also saved our secrets in Doppler. So let’s move on to our server setup. I have hosted the UI for this project on my Github page. To follow along, be sure you’ve cloned the [repository](https://github.com/icode247/authWithDoppler).
After cloning the repository to your development environment, install the dependencies by running the command:


    npm install

Then run the command below to start the project:


    npm start

So, here is the project structure of our application.

📦Authentication
┣ 📂controllers
┃ ┣ 📜googleAuth.js
┃ ┗ 📜passportAuth.js
┣ 📂middlewares
┃ ┗ 📜authMiddleware.js
┣ 📂public
┃ ┣ 📂css
┃ ┃ ┗ 📜style.css
┃ ┗ 📂img
┃ ┃ ┗ 📜undraw_settings_tab_mgiw.svg
┣ 📂views
┃ ┣ 📂includes
┃ ┃ ┗ 📜header.ejs
┃ ┣ 📜app.ejs
┃ ┗ 📜signin.ejs
┣ 📜.gitignore
┣ 📜doppler.yaml
┣ 📜index.js
┣ 📜package-lock.json
┗ 📜package.json

Now let’s move over to handling our user's authentication with Google and Facebook Authentication.

## Configuring Passport 

To authenticate your users with Passport, you need to install some packages. To get started, install these packages with the command below :


    npm install passport passport-google-oauth20 passport-facebook cookie-parser express-session

Wait for the installation to finish.
Next, open the root **index.js** file, and import the modules into the application.


    const passport = require('passport')
    const session = require('express-session')
    const cookieParser = require('cookie-parser')

After that, we need to set up our session middlewares for passports to authenticate and save our users' sessions.


    //configure app sessions
    app.use(cookieParser());
    app.use(passport.initialize());
    app.use(session({
       secret: 'keep it screet',
       resave: false,
       saveUninitialized: false
    }));
    app.use(passport.session());

## Creating our Routes 

We will be adding two more routes to the application, one for the success login success page and the user logout. But first, we need to create a middleware to protect the success page from unauthorized users. So create a **middleware/authMiddleware.js** file, then add the code below to it.


    //confirm user is logged in
    exports.confirmAuthentication = (req, res, next) => {
       if (req.isAuthenticated()) {
           return next();
       }
       res.redirect('/')
    }

Now, create the logout and the success page routes. Open your **index.js** root file and add this code below to it.


    app.get('/app', authMiddleware.confirmAuthentication, (req, res) => {
       res.render("app.ejs")
    })
    app.get('/logout', (req, res)=>{
       req.logout()
       res.redirect('/')
    })

Next, create the routes for your both Facebook and Google authentication with the code below:


    //Google Auth routes
    app.get('/auth/google', passport.authenticate('google', { scope: 'email' }));
    app.get('/auth/google/callback',
       passport.authenticate('google', {
           successRedirect: '/app', failureRedirect: '/'
       }));
    
    //Facebook Auth routes
    app.get('/auth/facebook', passport.authenticate('facebook', { scope: 'email' }));
    app.get('/auth/facebook/callback',
       passport.authenticate('facebook', {
           successRedirect: '/app', failureRedirect: '/'
       }))

Finally, let's create the view for the success page. Open the views directory, and create an app.ejs file. Then add the code below to it.


    <%- include('./includes/header') -%>
    <body>
       <div id="container">
          <div class="details">
              <h4>Success!, You are logged in</h4>
          </div>
          <a href="/logout" class="btn btn-danger">Logout</a>
       </div>
    </body>
    </html>

## Creating Google Authentication

Now that we have created our authentication routes, the next step is to configure the passport to authenticate our users with Google. 
First, we need to load our environment variables from Doppler to our Node.js environment. To do that, you need to create a **doppler.yaml** file in your project root directory. Then add the code below to it.


    setup:
      project: authwithdoppler
      config: dev 

We just created a Doppler repo configuration file, specifying our project name, and environment.
Now, open your terminal and run the command below on your application root directory.


    doppler setup

Doppler will ask if you want to use the settings from the repos config file, press **Y** and the **Enter** key.
Finally, create a **controller/googleAuth.js** file. Then add the code below to it.


    const passport = require("passport");
    const FacebookStrategy = require('passport-google-oauth20').Strategy
    
    const configGoogleAuth = () => {
    
       passport.use(new FacebookStrategy({
           clientID: process.env.GOOGLE_CLIENT_ID,
           clientSecret: process.env.GOOGLE_CLIENT_SECRET,
           callbackURL: 'http://localhost:4000/auth/google/callback',
       },
           function (accessToken, refreshToken, profile, done) {
               return done(null, profile)
           }
       ));
    
       // Passport session setup.
       passport.serializeUser(function (user, done) {
           done(null, user);
       });
    
       passport.deserializeUser(function (id, done) {
           done(null, id);
       });
    
    }
    module.exports = configGoogleAuth;

## Creating Facebook Authentication

Now we are done with Google authentication. So let's move over to Facebook. On your controller directory, create a new file **facebookAuth.js**. Then add the code below to it.


    const passport = require("passport");
    const FacebookStrategy = require('passport-facebook').Strategy
    
    const configFacebookAuth = () => {
    
       passport.use(new FacebookStrategy({
           clientID: process.env.FACEBOOK_APP_ID,
           clientSecret: process.env.FACEBOOK_APP_SECRET,
           callbackURL: "http://localhost:4000/auth/facebook/callback"
       },
           function (accessToken, refreshToken, profile, done) {
               return done(null, profile)
           }
       ));
    
       // Passport session setup.
       passport.serializeUser(function (user, done) {
           done(null, user);
       });
    
       passport.deserializeUser(function (id, done) {
           done(null, id);
       });
    }
    module.exports = configFacebookAuth;

At this point, our Facebook and Google authentication application is ready. Go ahead, restart the server and test the application on [localhost:4000](https://localhosts.mobi/4000).

![](https://lh5.googleusercontent.com/Ab6Qh_sUGXHqio4a2GxkYNmd2ineGh0I9QoLpu-1vuLp1Bl3etUFS4xFS07WdqG8gbHErIrLnNYB5-gu84NW2y3G9Bst5Mc5FLnG7AztpSVVqf9p2CUna0S6uN9QxG2efBpYLXnd=s0)


## Conclusion

Throughout this tutorial, you’ve learned how to create user authentication with Facebook and Google authentication. You created a Dopper account, installed the Doppler CLI. You’ve also known how to Create a Google and a Facebook App for your applications.
Now how would you manage secrets in your application? Perhaps you can learn more about secret management with Doppler.