Saturday, May 29, 2021

Authorization to data using middleware

 We can keep the token verification in every route and provide access on verification or send 401 error.

But, instead of writing in every route, we can keep in middleware also.


Create a separate middle ware for this.


middleware/auth.js

const jwtrequire('jsonwebtoken');
const config = require('config');

function auth(req,res,next){
    const token = req.header('x-auth-token');
    if(!tokenreturn res.status(401).send('Access denies, No token');
    try{
        const decoded = jwt.verify(token,config.get('jwtPrivateKey'));  
        req.user = decoded;//whichever the payload in token gneeration, will be retrieved in decoded.
        next();      
    }
    catch(ex){
        res.status(400).send('Invalid token');
    }
}

module.exports = auth;

To existing routes which we want to protect selectively, pass it as a parameter.First parameter will be the route from 2nd onwards, it will pass data to one by one middlewares.

Earlier route:

app.post("/api/courses", (reqres=> {

    console.log(req);

  const course = {
    id: courses.length + 1,
    name: req.body.name,
  };
  courses.push(course);
  res.send(course);
});

Modified one:

auth = require('middleware/auth');
app.post("/api/courses", auth, (reqres=> {

    console.log(req);

  const course = {
    id: courses.length + 1,
    name: req.body.name,
  };
  courses.push(course);
  res.send(course);
});

Then in the header provide x-auth-token value and pass the data from post man.


No comments:

Post a Comment