我不熟悉 Hapi
身份验证并尝试使用 this连接到 Twitter API 的教程,如教程中所述,要使代码正常工作,您必须从 Twitter 应用程序复制消费者 key 和消费者 secret ,然后将它们添加到 Twitter 身份验证策略中的代码版本
.
我的 server.js 看起来像这样(更改了客户端密码和客户端 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 调试代码,但看起来不起作用。我该怎么办? 谢谢
最佳答案
我首先认为您正在使用我的教程中列出的较新版本的 npm 软件包(bell
、boom
...)。
所以我尝试了你的代码,它工作没有任何问题 - 使用最新版本的软件包和旧版本。
我认为您可能遇到网络问题,例如代理等。
关于javascript - Node js - 使用 Bell 进行 Hapi JS 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36067603/