JWT Token Auth | JSON Web Tokens in Node.JS

When you create a REST service or any backend server for a website or an app, there is one talk about this new trending method for authenticating the user who is requesting your servers for data.

  Previously there were only a few ways to know where is the request coming from. That could be storing cookies, sessions in browsers, and using them to identify the user. So this method evolved, the trick is to create a string that has info of the user and data about the user.

  So JWT has payload, header, and signature which has info of the user and other important data. Why JSON you ask? because JSON is less verbose than XML and when encoded the size is small to easily use in HTTP transmissions.

The authorization token is passed as:
 Authorization: Bearer <token>


How it works?

  1. User signs in with username and password. 
  2. The server creates a JWT using one of the algorithms (HMAC, RSA, or ECDSA).
  3. Then this token is sent to the user and every interaction excepts a token in the header              
  4. The user can then store the token, and send it with every request
  5. If the user fails to do this, he/she has to reauthenticate with the server to obtain the token.

Diagram

Now some code:

I have created an express app in Node.JS. And some endpoints will listen:

/login: simple login with username and password, here we will create the JWT. /getData: get a request to get some data from the server.

1. Create a login endpoint, accept username and password, and send back the token.
const tokenVerification = require('./tokenVerify');
const jwt = require('jsonwebtoken'); // library for creating token
const privateKey = "my_secret_key"; // store this is env var, look at 'dotenv' on npm
// login user: email and password
app.post('/login', (req, res) => {
var email = req.body.email;
var password = req.body.password;
// syntax (basic)
// jwt.sign(<any-object>, <your-key>, <callback>)
// you can also define algo for sign check out: https://www.npmjs.com/package/jsonwebtoken
// signing in the jwt and sending it back to the user in the body
jwt.sign({ user : email }, privateKey, (err, token) => {
if (err) {
console.log("TOKEN GEN :: " + err);
res.status(500); // server died
} else {
res.json({ message: "1", data: result.insertId, token: token });
}
});
})
view raw routes.js hosted with ❤ by GitHub

2. Create a verification function, keep it separate so that you can play with it later

const jwt = require('jsonwebtoken');
const privateKey = "my_secret_key"; // store this is env var, look at 'dotenv' on npm
// exporting this function to call it runtime
module.exports = (req, res, next) => {
// reading the token from the header and verifying the token
var bearerHeader = req.headers["authorization"];
if(typeof bearerHeader !== 'undefined'){
var bearerToken = bearerHeader.split(" ")[1]; // extracting the token from: authorization: 'Bearer eyp..'
/**
* verifying the JWT token using the PK, if err occurs
* forbidden request 403 code
* @bearerToken : string, token from header
* @privateKey : string, constant secret key for decryption
* @payload : data, data saved while creating the token
*/
jwt.verify(bearerToken, privateKey, (err, payload) => {
if(err) res.status(403).json({message : err.message});
else next() // authorized
})
}else res.status(403); // unauthorized
}
view raw tokenVerify.js hosted with ❤ by GitHub


3. Another endpoint that checks the token, now it is fairly simple just add our function as middleware

const tokenVerification = require('./tokenVerify');
const jwt = require('jsonwebtoken');
/*
* tokenVerification : this is the function we made that check the token
* great cleaner code... I know
*
*/
app.post('/getUser', tokenVerification, (req, res) => {
// here user is already verified
res.json({ data: "you are real ;)" });
})
view raw routes.js hosted with ❤ by GitHub


Popular posts from this blog

Audio de-noising using Python (Wavelets)

Converting HTML5 Game for Android | 2 Methods

Display a table in JFrame UI from MySQL Table