我已经阅读了hapi-auth-cookie的文档,试图在我的网站中进行验证。
该cookie设置好了,我可以在我的chrome browser dev tools application tab
中看到它
但是当我console.log request.auth.credentials
时,结果为空
我要完成的操作是将用户限制为http://localhost:3000/restricted,我认为缺少的链接是request.auth.credentials
,因为它空
这是我的代码
const users = [
{
username: 'john',
password: '$2b$10$nrkw6Mco2j7YyBqZSWRAx.P3XEZsZg3MNfma2ECO8rGMUTcF9gHO.', // 'secret'
name: 'John Doe',
id: '2133d32a'
}
];
await server.register(require('hapi-auth-cookie'));
//strategy
server.auth.strategy('session', 'cookie', {
cookie: {
name: 'sid-example',
password: '!wsYhFA*C2U6nz=Bu^%A@^F#SF3&kSR6',
isSecure: false
},
redirectTo: '/login',
validateFunc: async (request, session) => {
const account = await users.find(
(user) => (user.id === session.id)
);
if (!account) {
return { valid: false };
}
return { valid: true, credentials: account };
}
});
server.auth.default({strategy: 'session', mode: 'try'});
//login post
server.route({
method: 'POST',
path: '/login',
handler: async (request, h) => {
console.log(request.payload)
const { username, password } = request.payload;
const account = users.find(
(user) => user.username === username
);
if (!account || !(await Bcrypt.compare(password, users[0].password))) {
console.log('user or password incorrect')
return h.view('login');
}
request.cookieAuth.set({ id: users.id });
console.log('login successful')
return h.redirect().location("/")
}
})
//restricted
server.route({
method: 'GET',
path: '/restricted',
options: {
auth: {
mode: 'required',
strategy: 'session'
}
},
handler: (request, h) => {
return new Promise ((resolve, reject) => {
let views = () => {
return h.view('restricted');
}
return resolve(views());
});
}
});
我尝试将options.auth.mode
内的restricted route
设置为“ try”,并尝试完全删除options
。
所有路由都可以正常工作,但是即使我已登录也无法打开受限路由。
请帮助
答案 0 :(得分:1)
您没有正确设置cookie身份验证,您的ID为未定义,将 users.id 替换为 account.id :>
request.cookieAuth.set({ id: account.id });