首页 > 解决方案 > 如何使用 Hapi/bell 登录 Twitter 用户?

问题描述

我正在尝试使用hapi/bell来设置 twitter 身份验证流程,但只是按照简单的示例进行操作,它似乎不起作用。这是我的基本代码:

'use strict';

const Hapi = require('@hapi/hapi');
const Bell = require('@hapi/bell');

const init = async () => {
  const server = Hapi.server({port: 3333, host: 'localhost'});

  // Register bell with the server
  await server.register(Bell);

  server.auth.strategy('twitter', 'bell', {
    provider: 'twitter',
    password: 'test_test',
    clientId: 'my_consumer_api_key',
    clientSecret: 'my_consumer_api_key_secret',
    isSecure: false 
  });


  server.route({
    method: 'GET', // Must handle both GET and POST
    path: '/bell/door', // The callback endpoint registered with the provider
    options: {
      auth: 'twitter',
      handler: function(request, h) {

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

        return h.redirect('/home');
      }
    }
  });

  server.events.on('request', (request, event, tags) => {
    if (event.channel === 'error') {
      console.dir(event.error.data, 4);
    }
  });

  await server.start();
  console.log('Server running on %s', server.info.uri);
};

// process.on('unhandledRejection', err => {
//   console.log(err);
//   process.exit(1);
// });

init();

这是我的应用程序的配置:

截图 2019-08-29 at 09 41 21

但是当我http://localhost:3333/bell/door使用浏览器访问时,我收到了这个错误:

 { Error: Failed obtaining twitter temporary credentials
    at exports.Client.internals.Client.internals.Client._request (/Users/ben/pro/tmp/authy/node_modules/@hapi/bell/lib/oauth.js:453:20)
    at process._tickCallback (internal/process/next_tick.js:68:7)
  data:
   { Error: Response Error: 403 Forbidden
       at internals.Client._shortcut (/Users/ben/pro/tmp/authy/node_modules/@hapi/wreck/lib/index.js:635:11)
       at process._tickCallback (internal/process/next_tick.js:68:7)
     data:
      { isResponseError: true,
        headers: [Object],
        res: [IncomingMessage],
        payload:
         <Buffer 3c 3f 78 6d 6c 20 76 65 72 73 69 6f 6e 3d 22 31 2e 30 22 20 65 6e 63 6f 64 69 6e 67 3d 22 55 54 46 2d 38 22 3f 3e 3c 65 72 72 6f 72 73 3e 3c 65 72 72 ... > },
     isBoom: true,
     isServer: false,
     output: { statusCode: 403, payload: [Object], headers: {} },
     reformat: [Function],
     typeof: [Function: Error] },
  isBoom: true,
  isServer: true,
  output:
   { statusCode: 500,
     payload:
      { statusCode: 500,
        error: 'Internal Server Error',
        message: 'An internal server error occurred' },
     headers: {} },
  reformat: [Function],
  typeof: [Function: internal] }

我究竟做错了什么?

标签: javascriptnode.jstwitter-oauthhapijs

解决方案


我有点晚了,但您需要更改您的消费者和客户端密钥。您当前正在设置“my_consumer_api_key”和“my_consumer_api_key_secret”。将它们替换为您可以在 twitter 应用程序中找到的值。

此外,您的回调方法是/login,您在 GET 路由中的路径是/bell/door。请更改其中之一以使其匹配。希望能帮助到你!


推荐阅读