节点js - 与Bell的Hapi JS身份验证

时间:2016-03-17 17:23:04

标签: javascript node.js twitter hapijs

我是Hapi身份验证的新手,并尝试使用this教程连接到教程中提到的Twitter API,以使代码工作到copy the Consumer Key and Consumer Secret from your Twitter application and then add them to your version of the code in the twitter auth strategy

我的server.js看起来像这样(更改了cliend secret和客户端ID以在此处发布):

 'use strict';

const Hapi = require('hapi');
const Boom = require('boom');

// Create a server with a host and port
const server = new Hapi.Server();
server.connection({
  port: 3000
});



server.route({
    method: 'GET',
    path: '/',
    handler: function (request, reply) {
        reply('Hello, world!');
    }
});

server.route({
    method: 'GET',
    path: '/{name}',
    handler: function (request, reply) {
        reply('Hello, ' + encodeURIComponent(request.params.name) + '!');
    }
});



// Register bell and hapi-auth-cookie with the server
server.register([require('hapi-auth-cookie'), require('bell')], function(err) {

  //Setup the session strategy
  server.auth.strategy('session', 'cookie', {
    password: 'secret_cookie_encryption_password', //Use something more secure in production
    redirectTo: '/auth/twitter', //If there is no session, redirect here
    isSecure: false //Should be set to true (which is the default) in production
  });

  //Setup the social Twitter login strategy
  server.auth.strategy('twitter', 'bell', {
    provider: 'twitter',
    password: 'secret_cookie_encryption_password', //Use something more secure in production
    clientId: 'lTIBJtiRT4G32wwMUYbU4yCRw',
    clientSecret: '6TBrWfoP4QEIB6lrApIxJun1SfLYb4e2fEs3vtrphFpB2FieGg',
    isSecure: false //Should be set to true (which is the default) in production
  });

  //Setup the routes (this could be done in an own file but for the sake of simplicity isn't)
  server.route({
    method: 'GET',
    path: '/auth/twitter',
    config: {
      auth: 'twitter', //<-- use our twitter strategy and let bell take over
      handler: function(request, reply) {

        if (!request.auth.isAuthenticated) {
          return reply(Boom.unauthorized('Authentication failed: ' + request.auth.error.message));
        }

        //Just store the third party credentials in the session as an example. You could do something
        //more useful here - like loading or setting up an account (social signup).
        request.auth.session.set(request.auth.credentials);

        return reply.redirect('/');
      }
    }
  });



  // Start the server

});





server.start((err) => {

    if (err) {
        throw err;
    }
    console.log('Server running at:', server.info.uri);
});

当我尝试打开此http://localhost:3000/auth/twitter

低于错误

{"statusCode":502,"error":"Bad Gateway","message":"connect ETIMEDOUT 10.10.34.36:443"}

还尝试使用console.log调试代码,但看起来它不起作用。我该怎么办? 感谢

1 个答案:

答案 0 :(得分:1)

我首先想到你正在使用我的教程中列出的更新版本的npm包(bellboom,...)。

所以我尝试了你的代码,它没有任何问题 - 使用最新版本的软件包和旧软件包。

我认为您可能会遇到类似代理的网络问题。