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 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 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.
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.
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 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 and create an App for your project. Then select Consumer depending on your application use case.
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.
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.
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.
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 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
.
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.
Next, fill in the information of your application, give it the name authWithDoppler
. Provide your email address, and your app logo.
Now, create your App credentials. On the credentials page, create an OAuth client ID credential for your App.
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.
Also, go back to your Google credentials page, copy your client ID and Client Secret and save them on Doppler.
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.
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.
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.
Top comments (0)