Skip to content

Instantly share code, notes, and snippets.

@Antoinebr
Last active October 26, 2018 21:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Antoinebr/ab77c8dbae09281e2ef0c979c2f2da87 to your computer and use it in GitHub Desktop.
Save Antoinebr/ab77c8dbae09281e2ef0c979c2f2da87 to your computer and use it in GitHub Desktop.
node-jwt.js

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);
});

Protect an API with JWT

const jwt = require('jsonwebtoken');

Create a route for getting a token (login)

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});
      
    })

});

My Midelware

/**
*
*  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();

  });
  

Protect a route with a midelware

Here we will protect a POST route

My Protected route

app.post("/api", verifyToken, (req, res) => {
       
  res.json({
    message : "Post Created",
    authData
  });
      
});
// server.js
// where your node app starts
// init project
const express = require('express');
const jwt = require('jsonwebtoken');
var app = express();
app.get("/api", (req, res) =>{
res.json({
message : "Welcome to the API"
});
});
app.post("/api", verifyToken, (req, res) => {
jwt.verify(req.token,'secretkey', (err, authData) => {
if( err ){
res.sendStatus(403);
return;
}
res.json({
message : "Post Created",
authData
});
});
});
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});
})
});
function verifyToken(req, res, next){
// Get Auth header value
const bearerHeader = req.headers['authorization'];
if( typeof bearerHeader === "undefined" ) {
res.sendStatus(403);
}
const bearerToken = bearerHeader.split(' ')[1];
req.token = bearerToken;
next();
};
// listen for requests :)
var listener = app.listen(process.env.PORT, function () {
console.log('Your app is listening on port ' + listener.address().port);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment