Introduction
These days if you are looking to build web services then you need to implement authentication so that your data is secured. Authentication is one of the big parts of every application and it can save your data from being misused.
Security tokens are becoming a standard way of applying security to web apis. Applying token based authentication is fairly easy method as client just need to send security token with every request is made to server.
You can view entire source code on Github from here
Software’s needed
- Node JS - Platform
- Postman – used for creating http requests like GET, PUT, POST, DELETE
- Sublime/Notepad++ - IDE for writing code.
Installing dependencies
We will be using jsonwebtoken npm package for creating web token and for verifying the same for the subsequent requests.
We have also used morgan which will help you do logging on console and this will make us to easily see what is happening inside our node application.
- Npm install express sequelize body-parser jsonwebtoken morgan
Setting up & Coding
- var express = require('express'),
- bodyParser = require('body-parser');
-
- var users = require('./users.json');
- var logger = require('morgan');
- var app = express();
- app.use(bodyParser());
- app.use(logger('dev'));
- var port = 8080;
- var jwt = require('jsonwebtoken');
- app.set('superSecret', "success is inevitable");
- var router = express.Router();
We will add authentication as a middleware in our node.js application. This will allow middleware to process any request coming to our application before it is passed to any specific route to handle. Within our middleware we will checking for valid token and if it is present in http header, request will be passed on specific route to handle.
- router.post('/authenticate', function(req, res) {
- var username = req.body.user;
- var password = req.body.password;
- var isUserFound = false;
- var foundUser = {};
- console.log(req.body.user + " " + req.body.password);
- for (var i = 0; i < users.length; i++) {
- if (users[i].user === req.body.user) {
- isUserFound = true;
- foundUser = users[i];
- }
- }
- if (isUserFound) {
- if (foundUser.password == req.body.password) {
- var token = jwt.sign(foundUser, app.get('superSecret'), {
- expiresInMinutes: 1440
- });
- console.log(token);
- res.json({
- success: true,
- message: 'Enjoy your token!',
- token: token
- });
- } else {
- res.json({
- success: false,
- message: 'Authentication failed. Wrong password.'
- });
- }
- res.send(foundUser);
- } else {
- res.json({
- success: false,
- message: 'Authentication failed. user not found.'
- });
- }
- });
We have added localhost:8080/api/authenticate as a route where you can get secure token if you are having valid credentials. We will be sending this token in http header of our request. This token could be used for subsequent request made to our application. Our token has a expire time and it could be set within the application.
I have created a user.json in which I will keep our valid user & their passwords. We will be loading this file in the starting and consuming it in our application.
-
- router.use(function(req, res, next) {
-
-
- var token = req.body.token || req.query.token || req.headers['x-access-token'];
-
-
- if (token) {
-
- jwt.verify(token, app.get('superSecret'), function(err, decoded) {
- if (err) {
- return res.json({
- success: false,
- message: 'Failed to authenticate token.'
- });
- } else {
-
- req.decoded = decoded;
- next();
- }
- });
- } else {
-
-
- return res.status(403).send({
- success: false,
- message: 'No token provided.'
- });
- }
- });
If token will not be present or token is expired or token is not valid then we will get an error.
- router.get('/users', function(req, res) {
-
- return res.json({
- status: 'OK',
- msg: "you are authenticated and all set to consume our services."
- });
-
- });
- router.use(function(req, res, next) {
-
- console.log('Something is happening.');
- next();
- });
-
- app.use('/api', router);
-
-
-
- app.listen(port);
- console.log('Magic happens on port ' + port);
We have added a test route which will help us to check the api against localhost:8080/api/user endpoint.
Testing our application
1. We are not sending any token
2. We are sending valid user to fetch token at /api/authenticate.
Request http msg
Response http msg
3. Our token is valid and we our GET request fulfilled. Token is send in http header when we are making any request.