【问题标题】:Hapi with Bell failed to authenticate to TwitterHapi with Bell 未能向 Twitter 进行身份验证
【发布时间】:2017-10-24 15:38:11
【问题描述】:

我已经构建了一些需要多重身份验证的基本后端 api。现在我正在尝试使用 Bell 连接到 Twitter API,但问题是不是显示页面来让我验证应用程序,而是显示错误 {"statusCode":500,"error":"Internal Server Error" ,"message":"发生内部服务器错误"}

以下是依赖文件:

index.ts

'use strict';

import * as hapi from "hapi";
import * as boom from "boom";
import router from './router/router';

const server: hapi.Server = new hapi.Server();
server.connection({ port: 3000, host: 'localhost' });

// .register(...) registers a module within the instance of the API. The callback is then used to tell that the loaded module will be used as an authentication strategy. 
server.register( [require( 'hapi-auth-jwt' ), require('hapi-auth-cookie'), require('bell')], ( err ) => {

    // normal server auth strategy using JWT
    server.auth.strategy( 'token', 'jwt', {  
        key: 'secretkey',
        verifyOptions: {
            algorithms: [ 'HS256' ],
        },
        redirectTo: '/login'
    } );

    //Setup the session strategy
    server.auth.strategy('session', 'cookie', {
        password: 'secret_cookie_encryption_password', //Use something more secure in production
        redirectTo: '/login', //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: 'secretkey',
        clientSecret: ' secretkey',
        isSecure: false //Should be set to true (which is the default) in production
    });

    //server.auth.default('token');

    // Make sure server get auth first before attach the router
    router.forEach( ( router ) => {
        console.log( `attaching ${ router.path }` );
        server.route( router );
    } );

} );



server.start((err) => {

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

router.ts

'use strict';

import controllers from '../server/controllers/Index';
import models from '../server/models/index';
import { compareHashPassword } from '../Helper';
import * as jwt from "jsonwebtoken";
import * as Boom from "boom";

// Init express router saja
let router;
let User = models.User;

// Setting API URL
router = [
    {
        method: 'GET',
        path: '/',
        config: {
          auth: {
            strategies: ['token', 'session'],        
        }, //<-- require a session for this, so we have access to the twitter profile
          handler: function(request, reply) {

            //Return a message using the information from the session
            return reply('Hello, ' + request.auth.credentials.displayName + '!');
          }
        }
    },
    {
        method: 'GET',
        path: '/login',
        handler: function(request, reply) {
            return reply('Please Login to ReviewUr!');
        }
    },
    // Authentication route for Token
    {
        path: '/auth',
        method: 'POST',
        handler: controllers.Auths.list
    },
    // Authentication route for Twitter
    {
        method: 'GET',
        path: '/auth/twitter',
        config: {
          auth: 'twitter',
          handler: function(request, reply) {

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


            const profile = request.auth.credentials.profile;

            request.cookieAuth.set({
              twitterId: profile.id,
              username: profile.username,
              displayName: profile.displayName
            });

            return reply.redirect('/').catch(error => reply(error));
          }
        }
    },
   ///////////////////////////////////////
];

export default router

我有什么遗漏吗?

【问题讨论】:

    标签: typescript twitter twitter-oauth hapijs


    【解决方案1】:

    您是否尝试将“/auth/twitter”路由移动到“/auth”上方,它似乎在“/auth/twitter”之前处理“/auth”。 您试图在哪条路线上显示用户登录选项? /登录 ?

    您是否尝试过不使用 jwt 或 auth-cookie,只使用 twitter?可能是其他插件有问题。

    这是我从实时应用中提取的实现。

    app-auth.js

    const Boom = require('boom');
    const internals = {};
    const config = require('config');
    
    exports.register = function (server, options, next) {
        server.auth.scheme('basic', internals.implementation);
        server.auth.strategy('simple', 'basic', true);
    
        // handle twitter login errors here
        server.ext('onPreResponse', function (request, reply) {
            const req = request.response;
            if (req.isBoom && request.path === 'login') {
                // there has been an error occurred during login process, sent user to home page
                server.log(['error', 'auth', 'twitter'], req.output.payload.error);
                return reply.redirect('/?error=103&account_error=' + encodeURIComponent(req.output.payload.error));
            }
    
            return reply.continue();
        });
    
        // twitter application registration
        server.auth.strategy('twitter', 'bell', {
            provider: 'twitter',
            password: config.get('twitter.pass'),
            clientId: config.get('twitter.key'),
            clientSecret: config.get('twitter.secret'),
            isSecure: config.get('authSecurity')
        });
    
        return next();
    };
    
    internals.implementation = function (server, options) {
    
        return {
            authenticate: function (request, reply) {
                // if there is no session information
                if (!request.yar.get('auth')) {
                    const headers = request.headers;
                    // if this request is xmlhttp then return as json
                    if (headers['x-requested-with'] === 'XMLHttpRequest') {
                        return reply(Boom.unauthorized("Please sign-in to system."));
                    }
                    return reply.redirect('/login');
                }
                return reply.continue({credentials: request.yar.get('auth')});
            }
        }
    };
    
    exports.register.attributes = {
        name: 'app_auth',    
        version: require('../package.json').version
    };
    

    twitter-route.js

    exports.view = {
        description: 'Twitter authentication handler',
        auth: 'twitter',
        handler: async (request, reply) => {
            // something went wrong
            if (!request.auth.isAuthenticated) {
                request.yar.flash('ERROR', request.auth.error.message);
                return reply.redirect('/login_error?error=103&account_error=' + encodeURIComponent(request.auth.error.message));
            }
    
            // profile information coming from twitter
            const profile = request.auth.credentials.profile;
    
            // do what ever you want with profile
    
        }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-30
      • 1970-01-01
      • 2015-09-23
      • 1970-01-01
      • 2016-02-24
      • 2011-08-04
      • 2018-05-03
      • 2012-08-06
      相关资源
      最近更新 更多