luk*_*tor 4 javascript express feathersjs
我正在使用feathers.js,并且我正在尝试将对support-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;
Run Code Online (Sandbox Code Playgroud)
但是,即使用户已登录,req.isAuthenticated()也会返回false.是否有办法将对公共目录中页面的访问权限仅限于已登录的用户?
要在页面加载方案中执行限制,您需要首先确保令牌位于cookie中.查看有关如何启用cookie 的feathers-authentication
文档.但是,通过cookie不要让自己暴露于CSRF攻击是非常重要的.
使用当前版本的feathers-authentication插件,您必须手动设置它.您需要从cookie中读取令牌以供渲染中间件使用:
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.');
}
});
Run Code Online (Sandbox Code Playgroud)
重要的是,您永远不允许任何服务直接使用cookie中的令牌.渲染中间件可以拉动令牌并使用它来制作服务请求,就好像它只是另一个客户端一样,但是你永远不会想要从cookie中取出它并将它放在req.feathers
对象上以便在服务内部进行授权.这就是你打开API到CSRF攻击的方式.
此外,如果您正在启用CORS,您很可能希望确保为渲染中间件禁用CORS.仅在您的Feathers服务之前启用CORS.
另一个缺点feathers-authentication@0.7.x
是cookie到期与令牌的到期不匹配.您需要手动设置Cookie的maxAge
到期时间,以匹配您希望令牌有效的时间,如文档中所述.
feathers-authentication@1.x.x
(目前处于预发布状态),将包括对服务器端渲染的更好支持,因此您不必自己连接它.它还将使用令牌使cookie过期.