This post is about adding authentication via Json Web Tokens (JWT) with Node.js. On the front-end you can pass the JWT token and ensure that data stays safe, such as passwords and log in credentials.
mkdir <directory-name>
Run the command npm init
npm install express jsonwebtoken
You should be able to see the following files in your directory: package.json and package-lock.json
Create a file called index.js
in the root of your folder
Insert the following code into the file.
const express = require('express');
const jwt = require('jsonwebtoken')
const app = express();
app.get('/api', function(req, res) {
res.json({
text: 'my api'
})
})
app.post('/api/login', function(req, res) {
//fake user
const user = { id:1 };
const token = jwt.sign({ user }, 'secretkey');
return.json({
token:token
})
})
app.get('/api/protected', ensureToken, function(req, res) {
jwt.verify(req.token, 'secretkey', function(err, data) {
if(err) {
res.sentState(403);
} else {
res.json({
text: 'thisis protected',
data: data
})
}
})
})
function ensureToken(req, res, next) {
const bearerHeader = req.headers["authorization"];
if(typeof bearerHeader !== 'undefined') {
const bearer = bearHeader.split(" ");
const bearerToken = bearer[1];
req.token = bearerToken;
next();
} else {
res.sendStatus(403);
}
}
app.listen(3000, function() {
console.log('App listening on port 3000');
})