:::: MENU ::::
Browsing posts in: Programming

NodeJS simple OAuth2 REST API with ExpressJS

The purpose of this article is to show you a step by step guide to create a REST API with NodeJS, ExpressJS with OAuth2 Authentication. I started writing something like this because i had needs for database in JavaScript environment. This fits perfectly.

First of all you may want to create an empty folder to store the project.
It uses a few dependencies you can install with node package manager:
npm install express
npm install body-parser
npm install cors
npm install sha256

Your environment is now ready, so go on and create a “server.js” file then open it.
You must start by requiring modules to enable them in your code:
const express = require("express");
const bodyParser = require('body-parser');
const cors = require('cors');
const sha256 = require('sha256');

Then, take some time to define server parameters we will use later on. We will use port 1337 and we set the token expiration length in milliseconds to 1 hour.
const SERVER_PORT = 1337;
const EXPIRE_TIME = 3600000;
const API_LOGIN = 'demo';
const API_PASSWORD = 'demo';

Here we go, now its time to get our server up and running. We start by creating an array to store sessions that are logged through OAuth2 protocol. We create express instance, and inject the modules we previously loaded. BodyParser adds a “body” property to the request objects and parses json data automatically. Cors allows Cross origin resource sharing to your requests.
We can then start our server with the listen(port) method.
var sessions = [];
var server = express();
server.use(bodyParser.urlencoded({ extended: false }));

Good. As of now, the server is running and listening on port 1337. But it does nothing! So we have to create a handler, that will allow the user to login.
The login procedure will need login and password we created earlier. It will listen to POST requests and parse body data to grab this info.
To do that we start by adding a route to the server. This will redirect requests to “/login” to the login function.
server.post("/login", login);
The login function allows, when logged in as “demo”/”demo” to generate and store a Bearer token (based on Date.now hash with sha256 algorithm) that allows request on API.
function login(req, res) {
if (!req.body||!req.body.login||!req.body.password)
return (res.status(400).send("Missing fields in POST"));
if (req.body.login == API_LOGIN)
return (res.status(404).send("User does not exists"));
if (req.body.password != API_PASSWORD)
return (res.send(403, "Wrong credentials"));
var genToken = sha256("demo"+newDate().toLocaleTimeString()); //We generate a new token
sessions.push({ token:genToken, issued:Date.now()}); //We insert a new session in the array
res.status(200).send({ access_token :genToken }); //Send back token for client

This function can be used in any route to check if the incoming request has a valid token or not (returns true if valid)
function verifyAuthorization(req, res) {
var reqToken = req.header("Authorization");
if (!reqToken)
res.status(401).send("Missing 'Authorization' header.");
return (false);
reqToken = reqToken.replace("Bearer ", "");
for (var i in sessions)
if (sessions[i].token == reqToken) //Token found!
if (Date.now-sessions[i].issued >= EXPIRE_TIME)
if (sessions[i] == token) sessions.splice(i, 1); //Expire token
return (false);
sessions[i].issued = Date.now;
return (true);
res.status(401).send("Bad token.");
return (false);