JSON WEB TOKEN for user authentication
JSON web tokens are one of the more popular ways to secure applications, especially in micro-services, but JWT is much more complex than a simple session ...
Node.js API Authentication With JWT
Adding User Login & JWT Signing | Creating a REST API with Node.js
7 minutes: Create a Node API with JWT's (json web tokens)
Build A Node.js API Authentication With JWT Tutorial
JWT (JSON Web Token) authentication is a popular way to authenticate users in web applications. Here's how to implement JWT authentication in Node.js:
npm install jsonwebtoken bcrypt dotenv
Create a configuration file (.env) to store environment variables:
SECRET_KEY=mysecretkey in .env file
Create a user.js model:
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const UserSchema = new mongoose.Schema({
email: { type: String, required: true },
password: { type: String, required: true },
});
UserSchema.pre('save', function(next) {
const user = this;
if (!user.isModified('password')) return next();
bcrypt.genSalt(10, (err, salt) => {
if (err) return next(err);
bcrypt.hash(user.password, salt, (err, hash) => {
if (err) return next(err);
user.password = hash;
next();
});
});
});
UserSchema.methods.comparePassword = function(candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, (err, isMatch) => {
if (err) return cb(err);
cb(null, isMatch);
});
};
module.exports = mongoose.model('User', UserSchema);
_____________________________________________________________
Create a auth.js controller:
const jwt = require('jsonwebtoken');
const User = require('../models/user');
exports.signup = function(req, res) {
const { email, password } = req.body;
const user = new User({ email, password });
user.save((err) => {
if (err) return res.status(400).json({ message: err.message });
const token = jwt.sign({ _id: user._id }, process.env.SECRET_KEY);
res.status(200).json({ token });
});
};
exports.login = function(req, res) {
const { email, password } = req.body;
User.findOne({ email }, (err, user) => {
if (err) return res.status(400).json({ message: err.message });
if (!user) return res.status(401).json({ message: 'User not found' });
user.comparePassword(password, (err, isMatch) => {
if (err) return res.status(400).json({ message: err.message });
if (!isMatch) return res.status(401).json({ message: 'Incorrect password' });
const token = jwt.sign({ _id: user._id }, process.env.SECRET_KEY);
res.status(200).json({ token });
});
});
};
____________________________________________________
JWT Authentication Tutorial - Node.js
🔴 Node JS Authentication & Cookies | JSONWebToken (JWT) with Nodejs & MongoDB in Hindi in 2020
7 minutes: Create a Node API with JWT's (json web tokens)
Node.js Authentication With JWT | Node JWT Authentication Example | NodeJS Tutorial | Simplilearn