【发布时间】:2017-10-14 16:33:21
【问题描述】:
我正在使用 HapiJS 和 Hapi-auth-cookie 策略为应用程序构建小型 REST 后端,但无法使其正常工作。我已经定义了这样的路线:
/ - 为应用程序的前端部分提供服务
/login - 为用户执行 mongodb 检查,然后比较密码,最后尝试设置 cookie
/restaurants - 我尝试使用 auth: 'session' 来保护它,但无法使其工作
我已经定义了策略(几乎从 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',
}
}
有什么想法吗?我已经花了两天时间试图弄清楚。
【问题讨论】:
标签: javascript node.js cookies session-cookies hapijs