未加星标

Token based authentication in Node.js using JWT

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二03 | 时间 2017 | 作者 红领巾 ] 0人收藏点击收藏

Token based authentication in Node.js using JWT

Authentication is a big part of any application. The way authentication is handled traditionally is by creating a user session on the server where we usually store the user’s information in memory or on disk. This is also known as server/session based authentication.

Web applications have come a long way in a past few year, we have the stateless web, hand-held devices came along, we have load balancer then came along the micro-services architecture. Storing session data on the server made our app less scalable and then sharing the session between multiple services or servers is also a problem. That is why Token Based Authentication

In this tutorial, we will learn to implement token based authentication in our node.js applications.

What is token based authentication?

Token-based authentication is state-less and session less, meaning when we authenticate the user we do not store any user information on the server. Instead, we generate a token signed by a private key and send it to the client. The way it works is as follows.

User makes a request to the server with username/password The server verifies the user. The server generates a signed token and provides it to the client. The token may contain the user data. The client stores the token and sends it along with every request. The server verifies the token and processes the request.

Tokens can be sent to server in any way but the best practice tells us to send it in an HTTP header .

DOWNLOAD

Our Application

In this tutorial, we will see how we can easily add token based authentication using JSON web Tokens in Node.js.

We will build a few APIs using NodeJS and ExpressJS and see how we can protect/authenticate them using JWT’s

We will be using.

MongoDB as our DB ExpressJS for routes jsonwebtoken an npm module for managing tokens. Getting started

Make sure you have node and npm installed. To begin with create a project folder and navigate into it and run npm init --yes . This will create a package.json for us.

Next, we will install the necessary tools for our application.

npm i body-parser express jsonwebtoken mongoose --save

Our, package.json should look like this.

package.json

{ "name": "jwt-auth", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "Rahil Shaikh", "license": "MIT", "dependencies": { "body-parser": "^1.15.2", "express": "^4.14.0", "jsonwebtoken": "^7.2.1", "mongoose": "^4.7.6" } } Folder Structure

We will be following the below folder structure

- config --- config.js - controllers --- index.js --- protected.js --- user.js - middlewares --- verifyToken.js - models --- user.js - index.js - package.json Creating our user model

We are using MongoDB for persistence and mongoose as our ORM. Make sure your machine has MongoDB installed and running.

./models/user.js

var mongoose = require('mongoose'); var Schema = mongoose.Schema; module.exports = mongoose.model('User', new Schema({ email: String, password: String })); Node Application

We will start in index.js by grabbing the required modules and setting up an express server.

./index.js

let express = require('express'); let app = express(); let bodyParser = require('body-parser'); let mongoose = require('mongoose'); global.config = require('./config/config'); let jwt = require('jsonwebtoken'); let User = require('./models/user'); mongoose.connect("mongodb://localhost/demo"); app.use(bodyParser.json()); app.get('/', function(req, res){ res.send('hello world'); }); app.listen(3000, function(){ console.log('App running on 3000'); });

Now, we can start the server by running node index.js . We should be seeing hello world printed on the screen on http://localhost:3000 .

Adding unprotected routes

In this section, we will expose an API to signup users and also to authenticate them. In the authenticate API we will create a token for a successful login and send it to the client.

./controllers/index.js

var express = require('express'); var router = express.Router(); router.use('/user',require('./user')); module.exports = router;

./controllers/user.js

let express = require('express'); let router = express.Router(); let jwt = require('jsonwebtoken'); let User = require('../models/user'); router.post('/signup', function(req, res){ let user = new User({ email: req.body.email, password: req.body.password }); user.save(function(err, data){ if(err){ return res.json({error: true}); } res.json({error:false}); }) }); router.post('/authenticate', function(req, res){ let data = { email: req.body.email, password: req.body.password }; User.findOne(data).lean().exec(function(err, user){ if(err){ return res.json({error: true}); } if(!user){ return res.status(404).json({'message':'User not found!'}); } console.log(user); let token = jwt.sign(user, global.config.jwt_secret, { expiresIn: 1440 // expires in 1 hour }); res.json({error:false, token: token}); }) }); module.exports = router;

Note. Here, for simplicity we are just encoding the entire user object. Idealy you should not include sensitive data such as password in your encoded token.

We will also have to modify our main index.js to add routes exposed by our controllers to the app.

... .... ..... app.use(require('./controllers')); app.listen(3000, function(){ console.log('App running on 3000'); });

Run the app. We will use postman to test our APIs. Let's signup first.


Token based authentication in Node.js using JWT
Sign Up Here, we have signed up a user with email as rahil[at]ciphertrick.com and password as password . Now, let's try to authenticate with the same credentials.
Token based authentication in Node.js using JWT
authenticate

If you see above, on a successful authentication the API sends us a token. This is the token we will need to further validate the user. We can accept the token in the header, in the body or as a url param. Also, remember the token has the data which we have signed using our secret key.

Note. In a real application passwords must not be stored as a plain text instead should be hased with a proper alogorithm depending upon your requirements.

Creating a middleware to verify Token

Let's add an express middleware that will verify the token for us.

./middlewares/verifyToken.js

var jwt = require('jsonwebtoken'); module.exports = function(req,res,next) { var tok

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

主题: Node.jsMongoDB
分页:12
转载请注明
本文标题:Token based authentication in Node.js using JWT
本站链接:http://www.codesec.net/view/524236.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(59)