How to authenticate user using JWTs (JSON WEB TOKEN) in NODE.JS

What is a JSON Web Token (JWT)?

JWT, access token, token, OAuth token.. what does it all mean??

Properly known as “JSON Web Tokens”, JWTs are a fairly new player in the authentication space. Being the cool new thing, everyone is hip to start using them. But are you doing it securely? In this article we’ll discuss user authentication best practices in Node.js using JWTs, while showing you how to use the nJwt library for creating and verifying JWTs in your Node.js application.


JWT is used to secure your application by randomly created the access key and secret. So the user’s client will supply the token on every subsequent request to your server. This allows the server to authenticate the request, without having to ask for credentials a second time (until the token expires, that is).

How to Create a JWT :

There are a few steps that you’ll to follow in order to create a JWT for a user, we’ll walk through each of these steps in detail:
  1. Generate the secret signing key
  2. Authenticate the user
  3. Prepare the claims
  4. Generate the token
  5. Send the token to the client
1- Generate the Secret Signing Key

To be secure, we want to sign our tokens with a secret signing key. This key should be kept confidential and only accessible to your server. It should be highly random and not guessable. In our example, we’ll use the node-uuid library to create a random key for us:

var secretKey = uuid.v4();

2- Authenticate the User

Before we can make claims about the user, we need to know who the user is. So the user needs to make an initial authentication request, typically by logging into your system by presenting a username and password in a form. It could also mean that they’ve presented an API key and secret to your API service, using something like the Authorization: Basic scheme.

In either situation, your server should verity the user’s credentials. After you’ve done this and obtained the user data from your system, you want to create a JWT which will “remember” the information about the user. We’ll put this information into the claims of the token.

3- Prepare The Claims

Now that we have the user data, we want to build the “claims” of the JWT. That will look like this:


var claims = {
  sub: 'user9876',
  iss: 'https://mytrustyapp.com',
  permissions: 'upload-photos'
}

Let’s discuss each of these fields. Technically speaking, you can create a JWT without any claims. But these three fields are the most common:

sub – This is the “subject” of the token, the person whom it identifies. For this field you should use the opaque user ID from your user management system. Don’t use personally identifiable information, like an email address.

iss – This is the “issuer” field, and it lets other parties know who created this token. This could be the URL of your website, or something more specific if your website has multiple applications with different user databases.

permissions – Sometimes you’ll see this as scope if the JWT is being used as an OAuth Bearer Token. This is simply a comma-seperated list of things that the user has access to do.

4- Generate the Token

Now that we have the claims and the signing key, we can create our JWT object :


var jwt = nJwt.create(claims,secretKey);
This will be our internal representation of the token, before we send it to the user. Let’s take a look at what’s inside of it:

console.log(jwt)

{
  header: {
    typ: 'JWT',
    alg: 'HS256'
  },
  body: {
    jti: '3ee9364e-8aca-4e39-8ba2-74e654c7e083',
    iat: 1434695471,
    exp: 1434699071,
    sub: 'user9876',
    iss: 'https://mytrustyapp.com',
    permissions: 'upload-photos'
  }
}

You’ll see the claims that you specified earlier, and many other properties. These are the secure defaults that our library is setting for you, let’s visit each one in detail:

alg – This declares how we’ve signed our token, in this case using the Hmac algorithm with a strength of 256 bits. If you want more security, you can bump this up to HS512

exp – This is the time that the token will expire, as a unix timestamp offset in seconds. By default our library sets this to 1 hour in the future. If you need to change this value, call jwt.setExpiration() and pass a Date object that represents the desired expiration time.

iat – This is the time that the token was created, as a unix timestamp offset in seconds.


jti – This is simply a random value, that is created for every JWT. We provide this in case you want to create a database of tokens that were issued. You may do this if you want to implement a token blacklist for tokens that you know have been compromised (i.e. a user tells you their account has been hacked into).

5- Send the Token to the Client

Now that we have the JWT object, we can “compact” it to get the actual token, which will be a Base64 URL-Safe string that can be passed down to the client.

Simply call compact, and then take a look at the result:

var token = jwt.compact();

console.log(token);

What you see will look like this:

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIyYWIzOWRhYS03ZGJhLTQxYTAtODhiYS00NGE2YmIyYjk3YWMiLCJpYXQiOjE0MzQ2OTY4MDEsImV4cCI6MTQzNDcwMDQwMX0.qRe18XcmNXB2Ily-U9dwF_8j9DuZOi35HJGppK4lpBw

This is the compact JWT, it’s a three-part string (separated by periods). It contains the encoded header, body, and signature.

How you send the token to the client will depend on the type of application you are working with. The most common use case is a login form on a traditional website. In that situation you will store the cookie in an HttpOnly cookie, so you can simply set the cookie on the POST response.

For example, if you’re using the cookies library for Express:

res.cookie('access_token',token,{httpOnly: true,secure: true   // for your production environment});
res.cookie('secret',secretKey,{httpOnly: true,secure: true    // for your production environment});
Once the client has the token, it can use it for authentication. For example, if you’re building a single-page-app, the app will be making XHR requests of your server. When it does so, it will supply the cookie for authentication.


How to Verify JWTs :

When a client has a token it will use it to authenticate the user. The token can be sent to your server in a cookie or an HTTP header, such as the Authorization: Bearer header. 


Suppose you are sending the token using cookie so every time when you made a http request from client you have to send it in the header. If you are using angular js for handle the http request in client side then you don't need to do much just passing a httpProvider you can do it easily like below :


YourAppName.config(function($routeProvider,RestangularProvider,$locationProvider,$httpProvider){

$httpProvider.defaults.withCredentials = true;

});

Once you set up the $httpProvider.defaults.withCredential to true then in every client http request you seen the cookie is also send like below screen shot -


Now you need to authenticate the token that comes in the http request from client in node js like below :


app.use(function(req, res, next) {
 var token = req.cookies.access_token;
 var secretKey = req.cookies.secret;
 nJwt.verify(token, secretKey, function(err,token){
   if(err){
  res.status(500).send({error: "You have not rights to enter in this restricted area."});
  return false;
   }else{
  next();
   }
 });

});

In the above code i just verify that the token is valid or not if not then i simple return a 500 error code with the message "You have not rights to enter in this restricted area.". Thats It !! 
In my next post you will see how to handle error in client side in angular js.

Thank you for reading this article. If you are facing any challenges while using this so please leave a question in the comment box i will reply you back as soon as possible.

Chears 
Happy Coding :)

Post a Comment

Previous Post Next Post