javascript - Feathers Js 在服务器端限制对页面的访问

标签 javascript express feathersjs

我正在使用 feathers.js 并尝试将对 payment-info.html 页面的访问限制为已登录的用户。

const app = feathers();

app.configure(configuration(path.join(__dirname, '..')));

app.use(compress())
  .options('*', cors())
  .use(cors())
  .use(favicon( path.join(app.get('public'), 'favicon.ico') ))

  .use('/payment-info.html', function(req,res,next){
  if(req.isAuthenticated()){
    next();
  } else {
    // 401 Not Authorized
    next(new Error(401));
  }
  })

  .use('/', serveStatic( app.get('public') ))
  .use(bodyParser.json())
  .use(bodyParser.urlencoded({ extended: true }))
  .configure(hooks())
  .configure(rest())
  .configure(socketio())
  .configure(services)
  .configure(middleware);

module.exports = app;

但是,即使用户已登录,req.isAuthenticated() 也会返回 false。有没有办法将对公共(public)目录中的页面的访问限制为仅登录的用户?

最佳答案

要在页面加载场景中进行限制,您首先需要确保 token 在 cookie 中。查看 feathers-authentication documentation了解如何启用 cookie。但非常重要的一点是,您要小心,不要通过 cookie 使自己遭受 CSRF 攻击。

使用当前版本的 feathers-authentication 插件,您必须手动设置它。您需要从 cookie 中读取 token 以供渲染中间件使用:

const jwt = require('jsonwebtoken');
const cookieParser = require('cookie-parser');

app.use(cookieParser());
app.use('/payment-info.html', function(req, res, next) {
  let token = req.cookies['feathers-jwt'];
  if (token) {
    // Get the JWT secret to verify the token.
    let secret = app.get('auth').token.secret;
    jwt.verify(token, secret, function(err, decoded) {
      if (err) {
        return res.status(401).send('You are not authorized to view that page.');
      }
      return next();
    });
  } else {
    return res.status(401).send('You are not authorized to view that page.');
  }
});

切勿让任何服务直接使用 cookie 中的 token ,这一点很重要。渲染中间件可以提取 token 并使用它来发出服务请求,就好像它只是另一个客户端一样,但您永远不想从 cookie 中提取它并将其放置在 req.feathers 服务内部授权对象。这就是您向 CSRF 攻击开放 API 的方式。

此外,如果您完全启用 CORS,您很可能希望确保为渲染中间件禁用 CORS。仅在您的 Feathers 服务之前启用 CORS。

feathers-authentication@0.7.x 的另一个缺点是 cookie 过期时间与 token 过期时间不匹配。您需要手动设置 cookie 的 maxAge 过期时间以匹配您希望 token 有效的时间长度,如文档中所述。

feathers-authentication@1.x.x(目前处于预发布阶段),将包括对服务器端呈现的更好支持,因此您不必自己连接它。它还将负责使 cookie 与 token 一起过期。

关于javascript - Feathers Js 在服务器端限制对页面的访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39908392/

相关文章:

node.js - FeathersJS:服务器到服务器身份验证

javascript - 正则表达式删除标记Notepad++内的特定文本

javascript - 用于计算标 checkout 现次数的 Twitter API

javascript - 如何在feathersjs中编写自定义查询/路由

mysql - 我们如何在sequelize中关闭数据库 `connection`

javascript - 我尝试安装express-generator,但收到一条奇怪的错误消息

dart - http url参数无效字符错误

javascript - 关闭并让关键字产生意外结果

javascript - 在 onload 函数中设置 Canvas 背景不起作用

node.js - 在 express.js 中验证用户数据后如何上传图像