Implement OAuth2 Server in Node.js

OAuth2 Authentication, is solution to secure your web API or Web application routes using token based authentication process. Here, I am assuming that you may have prior knowledge about OAuth2 Authentication process. If you are not clear about how it works then I would suggest you to read this article.

You will require 4 schemas/models OAuth2 server to work in Node.js. We will use mongoDB to store all information.

  1. oauth_clients – this model will be used to check for clientId and clientSecret.
  2. oauth_auth_codes – this model will store authentication codes generated for specific clientId.
  3. oauth_access_tokens – this model will store access token for specific clientId/clientScret.
  4. oauth_refresh_tokens – this model will store refersh_token generated based on existing token after expiration period.

 

Install Modules

Now, in your node application we will use following modules. In your project directory install following node modules.

1. Install express using npm install express --save

2. Install body-parser using npm install body-parser --save

3. Install oauth2-server using npm install node-oauth2-server --save

3. Install mongoose using npm install mongoose --save

Prepare Models

In Models we will need to create node module which will have following methods in it.

  • getAuthCode
  • saveAuthCode
  • getAccessToken
  • saveAccessToken
  • saveRefreshToken
  • getRefreshToken
  • getUser
  • getClient
  • grantTypeAllowed

Uhhh, lot of stuff!

To make this simpler we will divide above methods in different sub modules and we will have one core module where all above mentioned methods will be utilized. Core module which we will need to export will look something similar to oAuth.js.

oAuth.js
var AuthCode = require(‘./oAuthAuthCode’);
var AccessToken = require(‘./oAuthAccessToken’);
var RefreshToken = require(‘./oAuthRefreshToken’);
var User = require(‘./user’);
var Client = require(‘./oAuthClient.js’);

// node-oauth2-server API
module.exports.getAuthCode = AuthCode.getAuthCode;
module.exports.saveAuthCode = AuthCode.saveAuthCode;
module.exports.getAccessToken = AccessToken.getAccessToken;
module.exports.saveAccessToken = AccessToken.saveAccessToken;
module.exports.saveRefreshToken = RefreshToken.saveRefreshToken;
module.exports.getRefreshToken = RefreshToken.getRefreshToken;
module.exports.getUser = User.getUser;
module.exports.getClient = Client.getClient;
module.exports.grantTypeAllowed = Client.grantTypeAllowed;

Refer this git repo to understand how to define models for Node-oAuth2-server module to work. All credit goes to Mekentosj BV.

Configure OAuth2 Server

var oAuthModels = require('./models');

app.oauth = oauthserver({
model: oAuthModels.oauth,
grants: ['password', 'authorization_code', 'refresh_token'],
debug: true
});

Setup Routes

app.all('/oauth/token', app.oauth.grant());
app.all('/oauth/authorize', app.oauth.authCodeGrant(function(req, next) {
// The first param should to indicate an error
// The second param should a bool to indicate if the user did authorise the app
// The third param should for the user/uid (only used for passing to saveAuthCode)
next(null, true, '585273a465f7eb444462eb16', null);
}));

Complete Code (Server.js)

var express = require('express'),
bodyParser = require('body-parser'),
oauthserver = require('node-oauth2-server');
var oAuthModels = require('./models');
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.oauth = oauthserver({
model: oAuthModels.oauth,
grants: ['password', 'authorization_code', 'refresh_token'],
debug: true
});
app.all('/oauth/token', app.oauth.grant());
app.all('/oauth/authorize', app.oauth.authCodeGrant(function(req, next) {
// The first param should to indicate an error
// The second param should a bool to indicate if the user did authorise the app
// The third param should for the user/uid (only used for passing to saveAuthCode)
next(null, true, '585273a465f7eb444462eb16', null);
}));
app.get('/', app.oauth.authorise(), function (req, res) {
res.send('Secret area');
});
app.use(app.oauth.errorHandler());
app.listen(3000, () => {
console.log('Express server started on port 3000'); // eslint-disable-line
});

Hire Us

Implement OAuth2 Server in Node.js was last modified: January 3rd, 2017 by admin
Share :