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.

1 comment: