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

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (129)

我已经阅读了hapi-auth-cookie的文档,试图在我的网站上进行验证。

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

但是当我在console.log中时request.auth.credentials,结果为null

我想要完成的是将用户限制为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.mode里面设置'尝试' restricted route并尝试options完全删除。

所有路线工作正常,但即使我已登录,也无法打开受限制的路线。

请帮忙

提问于
用户回答回答于

您没有正确设置cookie认证,您的ID是不确定的,更换users.idaccount.id

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

扫码关注云+社区

领取腾讯云代金券