In this article, we will learn how to implement JWT authentication example with Express, Sequelize & MySQL in node js(Node Js JWT Authentication Tutorial with Example). so we will give you a simple example of how to generate jwt token in node js(jwt node js example).
In this example, we use the Jsonwebtoken(JWT) npm package for authentication in Node.js(JWT Authentication with Node js). we will show you step by step to create Node.js Restful CRUD API with JWT authentication, Sequelize with MySQL.
So you can see our node js example.
Application Directory Structure
We have created the best directory structure for the rest API CRUD operations. so you can follow the directory structure below.
/nodejs_rest_api /app /config db.config.js env.js /controller user.controller.js /middleware auth.js /model user.model.js /route user.route.js /node_modules package.json server.js
Create Node Js Application
First, we will open the command prompt and create the application in our directory. for this, you can follow the below command.
mkdir nodejs_rest_api cd my_node_app
The run “npm init” command through we can create a new package.json file in our application directory
npm init name: (nodejs_rest_api) version: (1.0.0) description: entry point: (index.js) server.js test command: git repository: keywords: author: license: (ISC) Is this ok? (yes) yes { "name": "nodejs_rest_api", "version": "1.0.0", "description": "", "main": "server.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node server.js" }, "keywords": [], "author": "", "license": "ISC" }
Install NPM Package
After the done setup node js application, we will install the express, sequelize, bcryptjs, body-parser jsonwebtoken, mysql2 and cors npm package. so you can see the following npm command.
npm install express sequelize mysql2 cors bcryptjs body-parser jsonwebtoken --save
Setup Express web server
In this step, We will create the server.js file in our application directory. after then setup the our application.
server.js
const express = require("express"); const cors = require("cors"); const bodyParser = require('body-parser'); const app = express(); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.use(cors()); const db = require('./app/config/db.config.js'); force: true will drop the table if it already exists db.sequelize.sync({force: true}).then(() => { console.log('Drop and Resync with { force: true }'); }); // api routes app.get("/", (req, res) => { res.json({ message: "Welcome to Our App." }); }); require('./app/route/user.route.js')(app); // set port, listen for requests const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server is running on port ${PORT}.`); });
Setting up Sequelize MySQL connection
In this step, we will create .env file and setup database connection using the sequelize with mysql.
app/config/env.js
const env = { database: 'myapidb', username: 'root', password: "", host: 'localhost', dialect: 'mysql', pool: { max: 5, min: 0, acquire: 30000, idle: 10000 } }; module.exports = env;
app/config/db.config.js
const env = require('./env.js'); const Sequelize = require('sequelize'); const sequelize = new Sequelize(env.database, env.username, env.password, { host: env.host, dialect: env.dialect, operatorsAliases: false, pool: { max: env.max, min: env.pool.min, acquire: env.pool.acquire, idle: env.pool.idle } }); const db = {}; db.Sequelize = Sequelize; db.sequelize = sequelize; //Models/tables db.users = require('../model/user.model.js')(sequelize, Sequelize); module.exports = db;
Create Sequelize model
Now, We create the sequelize model and which is define database schema to this sequelize model. so you can see user.model.js file as example.
app/model/user.model.js
module.exports = (sequelize, Sequelize) => { const User = sequelize.define('users', { firstname: { type: Sequelize.STRING }, lastname: { type: Sequelize.STRING }, email: { type: Sequelize.STRING }, password: { type: Sequelize.STRING } }); return User; }
Create controller
Here, we create some different methods such as findall, findById, update, delete, signup and signin. which is helpful for getting data, insert data and update data with mysql. here all data access by using token. means if you access any route then you must sign in and get the token and for every request you must pass the token. after then you can access it.
app/controller/user.controller.js
const db = require('../config/db.config.js'); var jwt = require("jsonwebtoken"); var bcrypt = require("bcryptjs"); const env = require('../config/env.js'); const User = db.users; // FETCH all Users exports.findAll = (req, res) => { User.findAll().then(users => { // Send all users to Client res.send(users); }); }; // Find a User by Id exports.findById = (req, res) => { User.findById(req.params.userId).then(user => { res.send(user); }) }; // Update a User exports.update = (req, res) => { const id = req.params.userId; User.update( { firstname: req.body.firstname, lastname: req.body.lastname, email: req.body.email }, { where: {id: req.params.userId} } ).then(() => { res.status(200).send({ message: 'updated successfully a user with id = ' + id }); }); }; // Delete a User by Id exports.delete = (req, res) => { const id = req.params.userId; User.destroy({ where: { id: id } }).then(() => { res.status(200).send({ message: 'deleted successfully a user with id = ' + id }); }); }; exports.signup = (req, res) => { //Check Email User.findOne({ where: { email: req.body.email } }).then(user => { if (user) { res.status(400).send({message: "Failed! Email is already in use!"}); }else{ //create User User.create({ firstname: req.body.firstname, lastname: req.body.lastname, email: req.body.email, password: bcrypt.hashSync(req.body.password, 8) }) .then(user => { res.status(200).send({ message: "User was registered successfully!" }); }) .catch(err => { res.status(500).send({ message: err.message }); }); } }); }; exports.signin = (req, res) => { User.findOne({ where: { email: req.body.email } }) .then(user => { if (!user) { return res.status(404).send({ message: "User Not found." }); }else{ var passwordIsValid = bcrypt.compareSync( req.body.password, user.password ); if (!passwordIsValid) { return res.status(401).send({ accessToken: null, message: "Invalid Password!" }); } var token = jwt.sign({ id: user.id }, env.JWT_ENCRYPTION, { expiresIn:60 * 60 * 24 // 24 hours }); res.status(200).send({ id: user.id, email: user.email, accessToken: token }); } }) .catch(err => { res.status(500).send({ message: err.message }); }); };
Create middleware for authentication
Now, we will create the JWT middleware in node js. which is every time check this route is authorized or not. so it is a very helpful file.
app/middleware/auth.js
const jwt = require("jsonwebtoken"); const env = require('../config/env.js'); const db = require('../config/db.config.js'); verifyToken = (req, res, next) => { let token = req.headers['x-access-token'] || req.headers['authorization']; if(token && token.startsWith('Bearer ')){ token = token.slice(7, token.length) } if (!token) { return res.status(403).send({ message: "A token is required for authentication" }); } jwt.verify(token, env.JWT_ENCRYPTION, (err, decoded) => { if(err){ console.log(err); return res.status(401).send({ message: "Invalid Token!" }); }else{ req.user = decoded.id; next(); //res.status(200).send({ message: "successs" }); } }); }; module.exports = verifyToken;
Create Route
Now, We will define all user’s routes. so you can see our route example.
app/route/user.route.js
const auth = require('../middleware/auth.js'); module.exports = function(app) { const users = require('../controller/user.controller.js'); // Retrieve all User app.get('/api/users',auth, users.findAll); // Retrieve a single User by Id app.get('/api/users/:userId', users.findById); // Update a User with Id app.put('/api/users/:userId',auth, users.update); // Delete a User with Id app.delete('/api/users/:userId',auth, users.delete); // User signup app.post('/api/user/signup', users.signup); // User signin app.post('/api/user/signin', users.signin); }
Run Node js Application
we will run the node js application using the below command. so you can follow the below command.
node server.js
Now you can run the example using the below Url in the browser.
http://localhost:3000/