Setting Up Twitter OAuth With Node and Passport JS

Sjlouji
The Startup
Published in
4 min readSep 29, 2020
Cover Image

In this blog, I will demonstrate how to implement Twitter OAuth with Node and Passport JS. To implement this, we will be using a third-party library called Passport JS. Passport JS is authentication middleware for Node and Express JS. Passport JS can be used with any Express JS applications. Passport JS provides 500 + strategies.

Table of Content

  1. Initialize a Node Project
  2. Creating Twitter OAuth Client Id
  3. Configure Twitter OAuth with Node
  4. Protecting Routes and Adding Logout view
  1. Initialize a Node Project

First, let’s create a new Node js Project. The below commands create a new folder and then initialize the node to our project.

mkdir twitter_passport
cd twitter_passport/
npm init -y
touch index.js

Now install the required packages:

npm i express cookie-session passport passport-twitter

After installing, copy the below code to your index.js file.

index.js

const express = require('express')
const app = express()
app.get('/',(req,res)=>{
res.send('Hello world')
})
app.listen(8000,()=>{
console.log('Serve is up and running at the port 8000')
})

Now start the server using node index.js. Then navigate to http://localhost:8000/. You should see “Hello world” displayed in the browser.

2. Creating Twitter OAuth Client Id

Before using the passport’s Twitter Authentication strategy, you should have registered your app or web application with Twitter. To do that, follow the steps below.

Navigate to the link:

https://developer.twitter.com/en/portal/dashboard

The link takes you to twitter’s developer dashboard. Now hit the Create Project button to create a new slack App.

Create App

Fill the walkthrough form and create a new app.

Create App walkthrough

Once done with creating a new App, click the view Keys button where you will see the API Key and Secret. Make a note of it.

View Client ID and secret

Then Add the callback URLs. Navigate to the Authentication settings and add callback URLs.

Add callback URL

3. Configure Twitter OAuth with Node

Now let’s start integrating Twitter Authentication with our project. To do that I am creating a new file named passport.js which holds the credentials that we created from Twitter’s OAuth page.

passport.js

const passport = require('passport');
const TwitterStrategy = require('passport-twitter').Strategy;
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
passport.use(new TwitterStrategy({
consumerKey: "xw************************Mb",
consumerSecret: "3m**************************************9h",
callbackURL: "http://www.localhost:8000/auth/twitter/callback",
},
function(accessToken, refreshToken, profile, done) {
return done(null, profile);
}
));

Copy and paste the below code to your index.js file.

The route /auth/twitter redirects the client to Twitter’s Login Page.

The route /auth/twitter/callback will act as a callback URL which will be called if the Twitter authentication is successful.

The route /ath/error will be called if any error has occurred during Twitter Authentication.

index.js

const express = require('express')
const app = express()
const cookieSession = require('cookie-session')
const passport = require('passport');
require('./passport')
const isLoggedIn = require('./Middleware/auth')
app.use(cookieSession({
name: 'twitter-auth-session',
keys: ['key1', 'key2']
}))
app.use(passport.initialize());
app.use(passport.session());
app.get('/',(req,res)=>{
res.send(`Hello world ${req.user.displayName}`)
})
app.get('/auth/error', (req, res) => res.send('Unknown Error'))app.get('/auth/twitter',passport.authenticate('twitter'));app.get('/auth/twitter/callback',passport.authenticate('twitter', { failureRedirect: '/auth/error' }),
function(req, res) {
res.redirect('/');
});
app.listen(8000,()=>{
console.log('Serve is up and running at the port 8000')
})

Now navigate to http://localhost:8000/auth/twitter. You will be redirected to Twitter’s login page. Upon logging into your Twitter account, you will be redirected back to our webpage and you will see your Twitter user name displayed on our webpage.

4. Protecting Routes and Adding Logout view

Now let’s add middleware to see if the user has logged in or not. To do that, I am creating a file named auth.js in the middleware folder.

Middleware/auth.js

const isLoggedIn = (req, res, next) => {
if (req.user) {
next();
} else {
res.status(401).send('Not Logged In');
}
}
module.exports = isLoggedIn

Once done, pass the middleware to the route /. Now navigate to the URL http://localhost:8000/. Automatically you will be redirected to the /auth/twitter route.

Now let’s create a function for logout. Just by calling the function req.logout() you can logout from the Twitter Account.

index.js

const isLoggedIn = require('./Middleware/auth')app.get('/',isLoggedIn,(req,res)=>{
res.send(`Hello world ${req.user.displayName}`)
})
app.get('/logout', (req, res) => {
req.session = null;
req.logout();
res.redirect('/');
})

Navigate to http://localhost:8000/logout. You will be logged out.

Feel free to contact me for any queries.

Email: sjlouji10@gmail.com.

Linkedin: https://www.linkedin.com/in/sjlouji/

Complete code on my GitHub:

Happy Coding …

--

--

Sjlouji
The Startup

Software Engineer at @Pando. Developer | Writer. From ABC to the world of code.