我是新的身份驗證與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
。Node js - Hapi與貝爾JS身份驗證
我server.js看起來是這樣的(改變cliend祕密和客戶端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調試代碼,但看起來不起作用。我該怎麼做? 謝謝
你能夠成功地向您的服務器上的其他網頁?嘗試刪除身份驗證要求以驗證您的服務器是否正常工作。 – colonelsanders
是的,我可以要求其他pages.i更新上面的代碼來顯示。 – Mojtaba