Authentication & Authorization in NodeJS using JSON Web Token

  • img
    Akshay Jayachandra Kumar
  • August 28,2019

Authentication is an act of showing the identity or proving the genuineness of the client to the server. For gaining access to a particular service, a client must themselves provide login credentials to the server for validation. If the information given by the client is proven valid, then the permission to access the requested service is granted which is called Authorization. Authorization is done from server side by sending back appropriate response to the client along with a Token.

Tokens are generated by hashing selected piece of information, provided by client as his authentication details, along with a secret key. Hashing is basically a one way process. Unlike encryption, one cannot generate back the information which was once given as the input for hash functions. Hence, tokens are unique for each clients.

The device/browser will save the token in its local storage, until it has been told to clear the token. On successive authentication step, the client can use the token to prove authenticity and get authorized for requesting services. The authentication using a token is similar to our normal day tokens. Only a valid token holder is allowed to access the service. Token authentication is mainly designed to be usable in single time login scenario. One the other side, the security and the authenticity of the user can be compromised if the token is lost or accessed by a third party.

JSON WEB TOKEN

JWT is an internet standard for creating JSON based web tokens. Let us have a look onto the process of token generation.

Suppose the details are stored in a json format,

{username:"akshayjk", password:"something"}

and is stored in a variable named clientDetails. We can generate the signature/hash value by passing the details and secret key to jwt.sign() function. By default the algorithm used for hashing is HMAC SHA256 (Hash-based Message Authentication Code - Secure Hash 256).

> var token = jwt.sign(clientDetails,'helloman'); //helloman is the secretkey.
> console.log(token);

Token obtained is given below.

>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaWQiOiJha3NoYXlqayIsInBhc3N3b3JkIjoic29tZXRoaW5nIiwiaWF0IjoxNTY3MDE0MDM4fQ.NT7bWC3xTDgqy-FFjl4TwGMISf_eHrhxNL4qY94p6E0

In above function, apart from details and secret key, we can specify the algorithm to be used and also the expiry of tokens.

>var token = jwt.sign(clientDetails, 'helloman',{algorithm: 'RS256'},{expiresIn:'1h'});

        //RSA -> Rivest-Shamir-Adleman cryptography
        //expiry is set to one hour

Above told examples are all in synchronous form. We can also do it in asynchronous form.

jwt.sign(clientDetails,'helloman',{algorithm: 'RS256'}, (err,token) => {
    console.log(token);
    });

sign() function will return 30—40 character long alphanumeric string as token. Hashing functions are always one to one because a slight variation in input can produce an entirely different output and no two inputs can have the same output. All these features resulted in hashing functions to be used in generating tokens.

Token generation on successful log-in

Once a token has been issued, client will only have to use the token for authentication process. Instead of sending details again, the client can send a token if he/she holds one. The token will be authenticated by the server. The hashing process is unidirectional, so the server won't be able to retrieve back login details of client from a token. So the authentication process is successfully achieved by comparison. Upon receiving the token, the server again produces the hash value for the client and compares it with the token which has been received. If the token value is found same, the token holder will be granted access. Otherwise the request for accessing service will be marked invalid.

A JSON Web Token structure contains 3 fields: Header, Payload, Signature.

  1. Header contains the details about algorithms on which signature is generated.
  2. Payload contains a set of claims, and customized claims can also be added. The information gathered from client to generate the signature will be present here.
  3. Signature is used to validate the token. It is produced by encoding the header and the payload with base64url encoding and concatenate both with the help of a period(.).

The payload details can be obtained by using a verify() function. Passing the token and secret key to the function will return the payload details, if no error is generated.

var user = jwt.verify(token,'helloman');
console.log(user.username);
console.log(user.password);

The above code has been written in synchronous form. We can also do it in asynchronous form.

jwt.verify(token,'helloman',(err,data) => {
        if (err)
            console.log(err);
        else{
            console.log(data.username);
            console.log(data.password)}
            });
Obtaining Payload back from JSON Web Token

This is how a token is generated and a user is validated on each successive log-in.

Tokens are of high importance, which is intended to be used by a particular client. Exposing those entities to a third party may lead to serious security issues or may even arise privacy problems.

This is all about authorization and authentication. I will be discussing much more things about security and data privacy on my future blogs.

Subscribe to newsletter
Need more tech news? Tune in to our weekly newsletter to get the latest updates