GitHub OAuth Authentication With Grant In NodeJS

Posted By : Hotam Singh | 27-Feb-2018

We often see in many applications, we need to extract user's information from other services or servers. Let's take an example where we need to build a web app and we need to authenticate a user with social accounts like (Github, Facebook, Linkedin, Stack Overflow Twitter etc). In such scenarios, we often need to get data from other servers. One of the best and efficient way to handle it via OAuth. It is good practice as never compromise with security.

In this article, we will be using GitHub for OAuth authentication. 

The steps involved in GitHub OAuth authentication are:

  • Register an application on GitHub.

  • Users are redirected to GitHub for users identification.

  • Users are redirected back to the main application by GitHub with the access token generated through the above process if successful.

  • Your app can now access the API with this access token.

 

Register an application:

 

Before we proceed with this article, we need to register our application on GitHub. To register an application, follow below steps:

In my case, I have created application with name oauth-github. Please see below image:

Now lets start the coding part for remaining steps as described above. Now follow below steps:

Install grant:

 

Install grant module for OAuth. Grant-express is an OAuth middleware for nodejs. Install this by npm install grant-express --save

 

Configure grant:

 

We need below parameters to configure grant :

Protocol: use http for local development or https for production.

Host: The server host (http://localhost:8082).

Github key: Github key or Client Id will be generated at the time when you will create or resiter your app on GitHub. You can check here for your application you created or regenerate it.

Github secret: GitHub secret will be generated on the same time when you register your app.

callback: is the most important parameter. This is the route invoked when user is authenticaed by GitHub. handle_github_callback is the GitHub callback url.

Now create a new file config.js and paste the below code. It is basic requirement to configure grant into our application.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
var env = process.env;

module.exports = {
    server: {
        protocol: "http",
        host: "http://localhost:8082"
    },
    github: {
        key: env.OAUTH_GITHUB_CLIENT_ID,
        secret: env.OAUTH_GITHUB_CLIENT_SECRET,
        callback: '/handle_github_callback',
        scope: []
    }
}
 

 

Creating server:

 

Now create our server. Create a new file app.js and paste below code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
'use strict';

//Loading environment variable from a file
require('dotenv').config({ path: '/etc/config/github-oauth/.env' });

//Requiring dependencies
var express = require('express')
    , session = require('express-session')
    , config = require('./config');

// Intanstiate the app    
var app = express();

// Configure grant
var Grant = require('grant-express');
var grant = new Grant(require('./config'));
app.use(session({ secret: 'grant' }));
app.use(grant);

app.listen(8082, function () {
    console.log('server running on port : 8082');
});

app.get('/', function (req, res) {
    res.send('Welcome to github-oauth example');
});

// Handling callback redirected from GitHub
app.get('/handle_github_callback', function (req, res) {
    const { error, error_description, error_uri } = req.query
    if (error) {
        res.status(500).json({
            error,
            error_description,
            error_uri
        })
    } else {
        console.log(req.query)
        res.end(JSON.stringify(req.query, null, 2))
    }
});
 

 

Run the app:

 

 

Start the flow:

 

Start the OAuth flow for GitHub, just navigate to http://localhost:3000/connect/github in your browser.

 

Issues:

 

You can face some of the below issues:

Issue 1: {"error": {"error": "Error: Grant: mount session middleware first"}}?

To fix this issue, just confiigure express-session middleware before configuring grant. See app.js :

Issue 2: {"error":{"error":"redirect_uri_mismatch","error_description":"The redirect_uri MUST match the registered callback URL for this application.","error_uri":"https://developer.github.com/apps/managing-oauth-apps/troubleshooting-authorization-request-errors/#redirect-uri-mismatch"}}

To correct this error, either provide a redirect_uri that matches what you had registered at registration time or leave it this parameter as default one registered with your application.

 

 

 

 

About Author

Author Image
Hotam Singh

Hotam has 1.5 years of experience in Node.JS. He has worked on Front End, JavaScript, Jquery, Backbone.JS, Database: MySQL, MongoDB. His hobbies are playing Sudoku/Puzzles and watching movies.

Request for Proposal

Name is required

Comment is required

Sending message..