Sunday, July 26, 2015

NodeJS API Authentication Using JWT

In my previous post I explained what is JWT and how to handle claim based authentication using that. In this post I will explain how to write simple NodeJS application using jwt-simple npm package.
First create blank nodejs application using visual studio like below.
Install following npm packages.
Create a folder called models and create User.js file like below.
In server.js file configure Access Token Headers like below.
Then write passport login function like below.
Next we need to write passport register function like below.
Next using jwt-simple npm packge, write following createSendToken function.
Next write register and login route functions like below.
We will create a new route called students and implement that like below.
Then set mongodb connection and listen for port 3000 in nodejs server like below.
Using Advanced Rest Client Chrome extension, we can test the application. First we will access students. Then we will get a unauthorized response.
Then register a user in the system like below. It will send a JWT token. Copy that to clip board. Because, to access students endpoint you need to send that token with headers.
Next access students endpoint like below. Send the JWT token in headers like below.

What is JWT?

API based software development has hugely increased. Now we need to think how are we going to secure API based application. In my previous post I explained how to use token based authentication. In this post we will look how to use JSON web tokens and how to secure api based applications using that.
JSON web tokens(JWT - pronounced as jot), work across difference programming languages. A JWT can be separated into three parts by a dot (.).
  • Header
  • Payload
  • Signature


Header contains, type and hashing algorithm.


Payload contains JWT claims. There are three claim types.

  • Registered claims
Claims that are not mandatory but whose names are registered for us. For example: The issuer of the token (iss), Subject of the token (sub), expiration of token (exp) and etc.
  • Public claims
These are claims defined by API owner. For example: Username and other important data.
  • Private claims
These are claims defined between producer and consumer of API.


The signature is made up of hash of following components.

  • Header
  • Payload
  • Secret (This value is held in server)

After that, in each request server needs to decode JWT and check payload claims.
According to claims, server can grant or deny functionalities.

Token Based Authentication

Reasons for token based authentication :
  • Stateless and salable servers
  • Mobile applications
  • Pass authentication to other applications (OAuth)
  • Extra Security
HTTP is a stateless protocol. Though we authenticate a user, application wont know about that user in next request. Traditional way is to store session data in the server. Usually in memory or stored in a disk. But this approach introduced lots of issues.
  • Server need to store session data (Overhead)
  • Session is store in the server. So issues come up when scaling the server
  • Mobile applications need to have CORS.
Steps of Token Based Authentication
  • User Requests Access with Username / Password
  • Application validates credentials
  • Application provides a signed token to the client
  • Client stores that token and sends it along with every request
  • Server verifies token and responds with data

Tuesday, July 21, 2015

Getting Started With Meteor.js

Meteor JS is a Full Stack javascript library which contain front-end libraries and NodeJS based server. Meteor allows us to build a web application quickly.You can follow the steps in MeteorJS site for install meteor into your machine.
In this post I will go through default meteor application.
First create a new meteor application called MyDemoApp.
Default file structure would look like below.
Using meteor command start the application.
Using Chrome developer tools you will be able to see source code.
But remember, this code is the source code after javascript code is executed. So, to view initial source code, right click on page and select View Page Source.
In here, you will see an empty body tag. Reason for that is, meteor engine will see the body tag as a meteor template. So, that template will inject when the DOM get loaded. In source code, there are lots of javascript flies are linked. Those are files from meteor core packages. And also it will contains third-party libraries.
In production release, all the files get minified in to one file like below.

Saturday, July 11, 2015

Lexical Scope and Closures

Lexical scope

Lexical scope means compile time scope. That means implicitly we can see what will be the scopes for each code. Most important thing to remember is, although javascript uses curly braces ({}), a new scope is created only when you create a new function.


Closure is when a function remembers it's lexical scope even when the function is executed outside that lexical scope.
In line 8, we pass "baz" function to "bam" function. Then "baz" function will execute outside of "foo" function. But still it has access to "bar" variable. That is a closure.

Friday, July 10, 2015

Javascript this keyword

Every function, while executing, has a reference it's current execution context, called this.

Default Binding

If you are in strict mode, default to this keyword is undefined. If  you are not in strict mode, default to this keyword is global object.
If we execute the code in strict mode, it will give following output.

Implicit Binding

In here this key word is automatically bind to the calling object.

Explicit Binding

If you use .call or .apply at the call side, the first parameter is this binding.

New keyword

When you put the new keyword, then function become a constructor call which means brand new object will be created and that object becomes the 'this' within the function call. In my previous post I explained about javascript new keyword.

Precedence of above rules with relates to this keyword

  1. Is it using new keyword?
  2. Is it using explicit binding?
  3. Is it using implicit binding?
  4. Is it using default binding?

Wednesday, July 8, 2015

Javascript new keyword

Following code should work fine.
But if we add new key word when we create an object then javascript runtime will automaticlly add highlighted code.

Javascript Mixing Pattern

In traditional object oriented languages we could write inherited classes and reuse functionality. However, in javascript, inheritance comes from chaining prototypes.  But for performance reason, you should not have long prototype chain. Therefore in javascript, for code reuse we can use mixing pattern. Multiple inheritance makes it easy by using mixing pattern.
The concept of mixing is to take an object and mixing the functionality with another object.
First we will define two objects.
Then we will define mixings.
Then we will define mixing function.
Now add mixing to the above objects and check the output.
Most important thing to remember is, you are injecting functionality to your code. Therefore you must document it properly in a large code base.

Javascript Inheritance Pattern

In javascript we do not have classes. We have objects. There's is only one way to make inheritance in javascript. That is by chaining prototype.
in the following example I have defined Person and Student objects where Student object inherit form the Person object.

Javascript Create Objects in Different ways.

Object Literals

In javascript we can create a object using object literals.
To store data we can define properties. In here I have showed four different ways to define properties.

Using Object.create

Another way to create objects in javascript is using Object.Create. Advantage is, it will allows to create objects which based upon other objects.
Now we will create objects which based on another object.
In above code, myBentleyCar's prototype is bentleyCar. We can verify that using following code.

Constructor functions

Another way to create objects in javascript is using constructor functions. In here name of the function should be begins with upper case letter, Then we can easily identify a constructor with other javascript functions. We can pass parameters using following way.
Then we define a method in this object. But reality is a property which contains a function object. But logically we could describe it as a method.
Using instanceof keyword we can determine whether an object is a instance of particular constructor.
The way we declare the method is not a proper way. Reason is there is a performance drawback in there. As I have mentioned that method is a new function object. So each time when we create a new object, this function object will be created.
And also it will give inheritance issues, if we define our methods in the constructor.
Instead of that, we can define methods in prototype. Any function that you define in the prototype will be shared across all the instances of that function.