server.js JWT Example
Reference
Steps/Notes
const express = require('express')
bring in the express libraryconst app = express()
setup (instantiate) the express serverapp.listen(<PORT>)
needs to be the last line of code inserver.js
and at a minimum you need to pass in a port numbersetup authenticate with JWT
example would be so only certain users can have access to posts and not just everyone
const jwt = require('jsonwebtoken')
bring in jwt libraryapp.use(express.json)
since json will be passed into the server from login route, need to allow the server to be able to read the json that gets passed up to it from the bodyjwt.sign(obj, TOKEN_SECRET)
serialize the obj with a JWTcreate a
ACCESS_TOKEN_SECRET
in the.env
filerequire('dotenv').config()
load.env
file
create a middleware function to attach to what ever routes we want to protect
attach
authenticateToken
middleware to all routes that need an authenticated user to accessauthHeader && authHeader.split(' ')[1]
checks for the presence of anauthHeader
and if there return the token portion of the authHeader array ([BEARER JWT_TOKEN]
) after it is split otherwise returns undefinedjwt.verify()
takes the token, SECRET and callback functionthe callback function which takes in the error and serialized obj parameters
next()
passes control on to the next piece of code whether that is another middleware or back to the main file
post.username === req.user.name
this will only add back the posts that belong to the authenticated user