Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to protect static folder in express with jwt

I have application which is build on nodejs and angularjs ,where i am using jwt token based authentication to authenticate and the api calls that is working fine

Even when the user is not login now application is service all the static resources how to avoid loading the application if the user is not login and redirect the user to login page

Finally i was able to fiqure it out in the app.js floder add the code sinpet app.use('/app/view/*', function(req, res, next) {

    if (!req.headers['authorization'] ) {
      res.sendfile('app/views/Error.html');

    } else {
      next();
    }
  });

this mean for the request coming with /app/view/ check if the header of the request contains the token generated with jwt

like image 550
Dhana Lakshmi Avatar asked Oct 30 '22 16:10

Dhana Lakshmi


1 Answers

If your JWT is stored in a cookie you can use a road like this one :

router.all('/*', function(req, res, next){
  if (!req.cookies.session) {
    return res.json("ERROR");
  }
  else {
    ValidateCookieFunction(req.cookies.session, function(auth_state) {
      if (!auth_state)
          return res.json("ERROR");
      else
          next();
    });
  }
});

else you can provide your JWT in an HTTP-Header

router.all('/*', function(req, res, next){
  if (!req.headers['x-access-token']) {
    return res.json("ERROR");
  }
  else {
    ValidateJWTFunction(req.headers['x-access-token'], function(auth_state) {
      if (!auth_state)
          return res.json("ERROR");
      else
          next();
    });
  }
});
like image 173
IggY Avatar answered Nov 15 '22 07:11

IggY