JWT Authentication with Node.js

const jwt = require('jsonwebtoken')const config = require('config')module.exports = function(req, res, next){// Get token from headerconst token = req.header('x-auth-token')// Check if no tokenif(!token){return res.status(401).json({msg: 'No token, authorization denied'})}//Verify tokentry {const decoded = jwt.verify(token, config.get('jwtSecret'))req.user = decoded.usernext()} catch(err){res.status(401).json({msg: 'Token is not valid'})}}
const express = require('express')const router = express.Router()const bcrypt = require('bcryptjs')const jwt = require('jsonwebtoken')const config = require('config')const { check, validationResult } = require('express-validator')const auth = require('../../middleware/auth')const User = require('../../models/User')
// @route GET api/auth
// @desc Get user by token// @access Publicrouter.get('/', auth, async (req, res) => {try {const user = await User.findById(req.user.id).select('-password')res.json(user)} catch(err){res.status(500).send('Server error')}})
// @route   POST api/auth// @desc    Authenticate User and get token// @access  Publicrouter.post('/',[check('email', 'Please include a valid email').isEmail(),check('password', 'Password is required').exists()],async (req, res) => {const errors = validationResult(req)
if(!errors.isEmpty()){return res.status(400).json({ errors: errors.array() })}const { email, password } = req.bodytry {let user = await User.findOne({ email })if(!user) {return res.status(400).json({ errors: [{msg: 'Invalid credentials'}] })}const isMatch = await bcrypt.compare(password, user.password)if(!isMatch){return res.status(400).json({ errors: [{msg: 'Invalid credentials'}] })}const payload = {user: {id: user.id}}jwt.sign(payload,config.get('jwtSecret'),{ expiresIn: 36000 },(err, token) => {if(err) throw errres.json({ token })})} catch(err){res.status(500).send('Server error')}})

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

New version of Total.js 4 framework (0.0.43)

The Big O

Unit, integration and e2e. What to write?

Why Node.Js Is Popular Amongst Developers?

Test 6

TypeScript library for Localazy API

Build and Package an NPM Component with esbuild, React and TypeScript

ESBuild, React and Typescript

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Amanda

Amanda

More from Medium

The Evolution of HTTP

How to Install SVN Server on Ubuntu 20.04 LTS & 21.10

Part 1. Install TypeScript + Node.js

hbase, zookeeper, sqoop, mysql Installation on Windows WSL 2 on Ubuntu 20.04 LTS (Single Node)