我正在使用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。有没有办法将对公共目录中的页面的访问限制为仅登录的用户?
要在页面加载场景中进行限制,您需要首先确保令牌位于 cookie 中。查看feathers-authentication
文档 https://docs.feathersjs.com/authentication/readme.html#cookie-options了解如何启用 cookie。但非常重要的是,您一定要小心,不要让自己遭受通过 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.');
}
});
切勿允许任何服务直接使用 cookie 中的令牌,这一点很重要。渲染中间件可以提取令牌并使用它来发出服务请求,就好像它只是另一个客户端一样,但您永远不会想从 cookie 中提取它并将其并置在req.feathers
服务内部授权的对象。这就是让 API 遭受 CSRF 攻击的方式。
此外,如果您要启用 CORS,您很可能希望确保渲染中间件禁用 CORS。仅在 Feathers 服务之前启用 CORS。
另一个缺点是[email protected] /cdn-cgi/l/email-protection
是 cookie 过期时间与 token 过期时间不匹配。您需要手动设置 cookiemaxAge
过期时间以匹配您希望令牌有效的时间,如文档中所述。
[email protected] /cdn-cgi/l/email-protection
(目前处于预发行版),将包括对服务器端渲染的更好支持,因此您不必自己连接它。它还将负责使 cookie 与令牌一起过期。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)