如何使用jwt保护Express中的静态文件夹

Dha*_*hmi 5 login node.js jwt angularjs

我有基于nodejs和angularjs构建的应用程序,其中我使用基于jwt令牌的身份验证进行身份验证,并且api调用正常运行

即使当用户现在不登录时,应用程序仍在为所有静态资源提供服务,如果用户未登录,如何避免加载应用程序并将用户重定向到登录页面

最终,我能够在app.js floder中将其添加到代码中。添加代码sinpet app.use('/ app / view / *',function(req,res,next){

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

    } else {
      next();
    }
  });
Run Code Online (Sandbox Code Playgroud)

这意味着对于/ app / view /附带的请求,请检查请求的标头是否包含用jwt生成的令牌

Igg*_*ggY 2

如果您的 JWT 存储在 cookie 中,您可以使用如下所示的路径:

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();
    });
  }
});
Run Code Online (Sandbox Code Playgroud)

否则你可以在 HTTP 标头中提供 JWT

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();
    });
  }
});
Run Code Online (Sandbox Code Playgroud)