gpt4 book ai didi

javascript - Hapi auth cookie 设置但 request.auth.credentials 为 null

转载 作者:行者123 更新时间:2023-12-02 23:52:30 25 4
gpt4 key购买 nike

我已阅读 hapi-auth-cookie 的文档,尝试在我的网站中进行验证。

cookie 设置,我可以在我的 chrome browser dev tools application tab 中看到它

但是当我console.log request.auth.credentials结果是

我想要完成的是将用户限制为 http://localhost:3000/restricted我认为缺少的链接是 request.auth.credentials因为它是null

这是我的代码

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.moderestricted route 内“尝试”并尝试删除 options总共。

所有路由都工作正常,但受限路由即使登录也无法打开。

请帮忙

最佳答案

您没有正确设置 cookie 身份验证,您的 ID 未定义,请将 users.id 替换为 account.id:

request.cookieAuth.set({ id: account.id });

关于javascript - Hapi auth cookie 设置但 request.auth.credentials 为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55578990/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com