首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >@hapi/bell (discord) --> @hapi/cookie鉴权切换

@hapi/bell (discord) --> @hapi/cookie鉴权切换
EN

Stack Overflow用户
提问于 2019-11-18 22:48:50
回答 1查看 300关注 0票数 1

我正在构建一个hapi(v18.4.0) API,我希望针对不一致的OAuth2服务对用户进行身份验证。我使用@hapi/bell(v11.1.0)来处理OAuth2握手。

我可以通过Discord进行身份验证,但我不能让@hapi/cookie(v10.1.2)接管身份验证责任。我可以看到cookie正在创建,但我唯一一次看到调用的cookie注销函数是通过“validateFunc”路由。我相信我已经为在localhost上进行开发设置了所有必要的标志。

基本上,我不能让cookie身份验证策略工作。令我惊讶的是,当我转到需要身份验证的路由时,我没有看到调用的validateFunc。

下面是我的身份验证策略设置、cookie validateFunc函数、登录/注销路由和测试路由。

谢谢你的帮助!

代码语言:javascript
复制
exports.plugin = {
  name: 'auth',
  dependencies: ['hapi-mongodb', 'bell', '@hapi/cookie'],
  register: (server, options) => {

    server.auth.strategy('session', 'cookie', {
      cookie: {
        name: 'sid-demo',
        password: SECRET_KEY,
        isSecure: false,
        isSameSite: 'Lax'
      },
      redirectTo: '/demo-server/api/v1/auth/login', //If there is no session, redirect here
      validateFunc: async (request, session) => {

        console.log("validating cookie...");
        const db = request.mongo.db;
        const ObjectID = request.mongo.ObjectID;

        try {
          const user = await db.collection(usersTable).findOne({ _id: new ObjectID(session.id) });
          if (!user) {
            console.log("no user found, cookie invalid");
            return { valid: false };
          }

          return { valid: true, credentials: user };

        }
        catch (err) {
          console.log("Validation error:", err);
          return { valid: false };        
        }
      }
    });

    server.auth.strategy('discord', 'bell', {
      provider: 'discord',
      password: SECRET_KEY,
      clientId: DISCORD_CLIENT_ID,
      clientSecret: DISCORD_SECRET,
      isSecure: false,
      isSameSite: 'Lax'
    });
  }
};
代码语言:javascript
复制
exports.plugin = {
  name: 'routes-auth',
  dependencies: ['hapi-mongodb', 'auth'],
  register: (server, options) => {

    server.auth.default('session');

    server.route({
      method: ['GET', 'POST'],
      path: '/demo-server/api/v1/auth/login',
      options: {
        auth: 'discord',
        handler: async (request, h) => {

          if (!request.auth.isAuthenticated) {
            console.log("authenticaion failed");
            return `Authentication failed due to: ${request.auth.error.message}`;
          }

          const db = request.mongo.db;

          const credentials = request.auth.credentials;
          const profile = request.auth.credentials.profile;

          try {
            const result = await db.collection(usersTable).findOne({ email: request.auth.credentials.profile.email });
            if (result) {

              console.log("user exists");

              request.cookieAuth.set({
                id: result.id,
                username: profile.username,
                token: credentials.token
              });

              return h.redirect('/demo-server/restricted');
            }
          }
          catch (err) {
            console.log(err);
            return Boom.serverUnavailable('database error');
          }

          console.log("user does not exists, registering new user");
          const user = {
            email: request.auth.credentials.profile.email,
            last_login: new Date(),
            username: request.auth.credentials.profile.username,
          };

          try {

            const result = await db.collection(usersTable).insertOne(user);

            request.cookieAuth.set({
              id: result.insertedId,
              username: profile.username,
              token: credentials.token
            });

          }
          catch (err) {
            return Boom.serverUnavailable('database error');
          }

          return h.redirect('/demo-server/restricted');

        },
        tags: ['auth', 'api']
      }
    });

    server.route({
      method: 'GET',
      path: '/demo-server/api/v1/auth/logout',
      options: {
        handler: (request, h) => {

          request.cookieAuth.clear();
          return h.redirect('/demo-server');
        }
      }
    });
代码语言:javascript
复制
exports.plugin = {
  name: 'routes-default',
  dependencies: ['auth'],
  register: (server, options) => {

    server.route({
      method: 'GET',
      path: '/demo-server',
      handler: (request, h) => {

        return h.response({ result: 'Welcome to demo-server!' }).code(200);
      },
      config: {
        description: 'This is default route for the API.',
        response: {
          status: {}
        },
        tags: ['default','test']
      }
    });

    server.route({
      method: 'GET',
      path: '/demo-server/restricted',
      handler: (request, h) => {

        return h.response({ message: 'Ok, You are authorized.' }).code(200);

      },
      config: {
        auth: {
          mode: 'try'
        },
        description: 'This is a default route used for testing the jwt authentication.',
        response: {
          status: {}
        },
        tags: ['default','test','auth']
      }
    });
  }
};
EN

回答 1

Stack Overflow用户

发布于 2019-11-20 00:24:07

找到问题所在...我需要设置API根目录的路径。

代码语言:javascript
复制
cookie: {
        name: 'sid-demo',
        password: SECRET_KEY, //Use something more secure in production
        path: '/demo-server', // <--- This was what fixed the issue
        isSecure: false,
        isSameSite: 'Lax'
      },
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58917173

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档