我正在为应用程序构建小型REST后端,使用HapiJS和策略,但无法使其正常工作。我已经定义了这样的路线:
/ -用于服务应用程序的前端部分
/login -为用户执行mongodb检查,然后比较密码,最后尝试设置cookie
/restaurants --我试图用auth来保护它:‘会话’,但无法使它工作
我已经定义了策略(几乎是从hapi-auth-cookie github页面复制过来的),但正如我注意到的,但是使用console.log,validateFunc传入的策略选项甚至一次都不会被调用。为什么?是我的主要问题还是代码的其他部分坏了?
一些代码示例:
会话的策略定义:
exports.register = function(server, options, next) {
const cache = server.cache({ segment: 'sessions', expiresIn: 3 * 24 * 60 * 60 * 1000 });
server.app.cache = cache;
server.auth.strategy('session', 'cookie', false, {
password: 'password-should-be-32-characters',
cookie: 'lun-cookie',
redirectTo: false,
isSecure: false,
ttl: 20 * 1000,
validateFunc: function (request, session, callback) {
cache.get(session.sid, (err, cached) => {
if (err) {
return callback(err, false);
}
if (!cached) {
return callback(null, false);
}
return callback(null, true, cached.account);
});
}
});
return next();
};
负责设置cookie的登录方法:
login: (request, reply) => {
const dbQuery = {
email: request.payload.email
};
UserSchema.findOne(dbQuery, (err, user) => {
if (err) {
return console.log(err);
}
if (!user) {
return reply(Boom.unauthorized());
}
Bcrypt.compare(request.payload.password, user.password, (err, res) => {
if (err) {
return console.log(err);
}
if (!res) {
return reply(Boom.unauthorized());
}
const sid = String(123);
request.server.app.cache.set(sid, { account: user }, 0, (err) => {
if (err) {
reply(err);
}
request.cookieAuth.set({ sid: sid });
return reply("ok");
});
})
});
}
由策略保护的路由定义:
{
method: 'GET',
path: '/restaurants',
handler: controller.getRestaurants,
config: {
validate: {
query: {
list: Joi.string().allow('full').optional(),
type: Joi.string().valid(restaurantTypeEnum).optional(),
}
},
auth: 'session',
}
}
有什么想法吗?我已经花了两天时间想办法解决这个问题。
发布于 2017-05-17 09:17:11
首先,确保hapi-auth-cookie在路由之前已注册。
然后,我会检查登录函数是否真的通过并回复一些cookie。
然后我会编辑“/餐馆”到auth: { mode: 'try', strategy: 'session' },
的路线
并检查request.headers是否包括cookie。
如果让它正常工作,请确保为它编写一些单元测试。
https://stackoverflow.com/questions/43987136
复制相似问题