Demo available : https://confused-stitch.glitch.me/
POST https://confused-stitch.glitch.me/api/login
POST (protected ) https://confused-stitch.glitch.me/api/ ( with correct headers )
var request = require("request");
var options = { method: 'POST',
url: 'https://confused-stitch.glitch.me/api/',
headers:
{ 'postman-token': '010a847b-819e-60d6-9ef4-a455d918b91f',
'cache-control': 'no-cache',
authorization: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7ImlkIjoxLCJuYW1lIjoiQW50b2luZSJ9LCJpYXQiOjE1NDA1ODc5NDUsImV4cCI6MTU0MDU4Nzk3NX0.CFLaQhd7__VBBeyAMxrrMS0c8UkwFYEbXhpZtlQqr7I' } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
const jwt = require('jsonwebtoken');
app.post("/api/login", (req, res) =>{
// Mock user
const user = {
id: 1,
name : "Antoine"
}
jwt.sign({user:user}, 'secretkey', {expiresIn : '30s' }, (err, token) => {
res.json({token : token});
})
});
/**
*
* OUR JWT MIDLLEWARE
*
*/
function verifyToken(req, res, next){
// Get Auth header value
const bearerHeader = req.headers['authorization'];
// check if the header exists
if( typeof bearerHeader === "undefined" ){
res.sendStatus(403);
return;
}
// split the header to extract the token
const bearerToken = bearerHeader.split(' ')[1];
// we verify the token
jwt.verify( bearerToken ,'secretkey', (err, authData) => {
if( err ){
res.sendStatus(403);
return;
}
next();
});
Here we will protect a POST route
app.post("/api", verifyToken, (req, res) => {
res.json({
message : "Post Created",
authData
});
});