2015-02-11 49 views
0

我们使用Hapi JS为我们的其余服务器。我们为Redis上的用户存储身份验证令牌。现在,如果由于某种原因节点与Redis失去连接,我们需要将401 Authorization failed错误返回给所有路由中的所有客户端,以便客户端可以自动注销。为hapijs返回所有路由的401错误

那么,有没有办法在不改变路由处理函数代码的情况下从所有路由返回401?

+0

你可以[删除所有的路线映射](http://stackoverflow.com/questions/10378690/remove-route-mappings-in-nodejs-express/28369539#28369539)并插入一个新的? – laggingreflex 2015-02-11 21:17:39

+0

对不起,无法准确理解删除所有映射的好处。我想我需要一个中间件来实现这一点。至少我需要hapijs中的中间件等价的机制。 – 2015-02-11 21:37:24

+0

目前为止,您如何进行身份验证? 如果您使用hapi认证机制,则应该发生这种情况...... – 2015-02-12 10:53:51

回答

0

您可以使用Hapi server extension event'onRequest'

var hapi = require('hapi'); 
var Boom = require('boom'); 

var server = new hapi.Server(); 
//Configure your server 

//Add an extension point 

server.ext('onRequest', function (request, reply) { 
    var status; 
    //Check status of redis instance 

    if (status) { 
     //Redis is running, continue to handler 
     return reply.continue(); 
    } else { 
     //Redis is down, reply with error 
     return reply(Boom.unauthorized('Auth server is down')); 
    } 
}); 

这可能不是你如何验证你的redis实例的状态,但我希望你明白了。

可以查找各种其他扩展点here

+0

是的,这正是我所做的。 – 2015-02-25 12:58:32

0

您应该在应用程序使用的auth插件中执行此操作。看看hapi-auth-basic的实现:https://github.com/hapijs/hapi-auth-basic/blob/master/lib/index.js

如果你看看这个方案,你必须定义一个认证方法,它接受请求和回复。这是你应该检查认证令牌的redis的地方。如果连接不可用,你应该

return reply(Boom.unauthorized('Authorization failed', 'Basic'));

希望这有助于。