Setup Github OAuth With Node and Passport JS

Sjlouji
The Startup
Published in
4 min readSep 22, 2020

--

Cover Image

As a developer, It’s very often we would have used Github accounts to login to a web application. The process would have been so simple. This blog will explain to you how to implement Github authentication with Node and Express 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.

  1. Initializing a Node JS Project

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

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

Now install the required packages.

npm install express cookie-session passport passport-github2 --save

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 getting displayed in the browser.

2. Creating an OAuth Client ID

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

Navigate to the below link.

The link navigates you to Github and then displays a form. After filling the form, hit the register application button which will redirect you to the page where we can get the Client ID and Secret.

Make a note of the Client ID and the Client Secret.

3. Configuring Github OAuth

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

passport.js

const passport = require('passport');
const GitHubStrategy = require('passport-github2').Strategy;
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
passport.use(new GitHubStrategy({
clientID: "f0*************c6",
clientSecret: "41**********************************bf",
callbackURL: "http://localhost:8000/auth/github/callback"
},
function(accessToken, refreshToken, profile, done) {
return done(null, profile);
}
));

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

The route /auth/github redirects the client to the Github Login Page.

The route /auth/github/callback will act as a callback URL which will be called if Github Authentication is Successful.

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

index.js

const express = require('express')
const app = express()
const cookieSession = require('cookie-session')
const passport = require('passport');
require('./passport')
app.use(cookieSession({
name: 'github-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/github',passport.authenticate('github',{ scope: [ 'user:email' ] }));app.get('/auth/github/callback',passport.authenticate('github', { 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/github. You will be redirected to Github’s Login page. On logging in to your Github account, you will be redirected back to our webpage and you will see your Github User name getting displayed on our webpage.

4. Protecting Route and adding a logout view

Now let’s add middleware to find 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/github route.

Now let’s create a function for logout. Just by calling the function req.logout() you can logout from the Github 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.