Github OAuth2 with passport and express

GitHub Authentication with passport and express.

We are going to create a (very)simple example of a gitHub login with passport and express. This tutorial will assume you have some bare minimum knowledge of express and node.

First you need to create Github clientId and clientSecret keys from Github website.

Go this link https://github.com/settings/applications/new

You will get your auth keys for your application. Save those keys but make sure you don’t publish them.

We will create a website with two pages: secret.html and login.html

Obviously our goal is to make secret.html only available if you login with github (from login.html)

Let me show you the content of those files first:

Now lets take a look at the server. I’ll put the different parts of the server.js file in line number order

I have added some tags with ‘flow #1, flow #2’ that explains how the process works from the moment you click ‘Sign in with GitHub’ link from login page.

node dependencies and github of your appkeys
passport configuration
express middleware
introduction to isAuthenticated function and how to use it
auth github methods

This is the final result in action.

Immediately when we try to access the root(http://127.0.0.1:4568/) page we get redirected to the login page:

Clicking on Sign in link will redirect us to Github:

If we authorize, we are redirected to the root page (secret.html):

Try this yourself and I’ll suggest you to take a look at the chrome dev tool Network tab. Also look at the headers of every API call. You will notice the auth cookie on it.

Please let me know if this is helpful, I will also appreciate some feedback. Thanks for reading.