2016-11-28 81 views
1

我们使用hapijs和oauth服务器进行身份验证。我们需要在hapijs中实施基于角色的授权。以下方式对hapijs来说不错。使用Hapijs和oauth 2的API授权流程

  1. 注册认证方案

    server.auth.scheme('custom', function (server, options) { 
    
        return { 
    
         authenticate: function (request, reply) { 
         // calling oauth flow for roles match 
        } 
    }); 
    
  2. 注册认证策略&添加auth,在server.route角色

    server.auth.strategy('default', 'custom'); 
    
    server.route({ 
        method: 'GET', 
        path: API_Path, 
        config: { 
         roles: ['ADMIN', 'USER'], 
         auth : 'default' 
        }, 
        handler: function (request, reply) {     
         return reply.act({ 
          role: 'admin', 
          cmd: 'getInfo', 
          id: request.params.id 
         }); 
        } 
    }); 
    

回答

0

你应该注册一个策略和验证类的凭据这个。

const validate = function (request, username, password, callback) { 
const user = users[username]; 
if (!user) { 
    return callback(null, false); 
} 

Bcrypt.compare(password, user.password, (err, isValid) => { 
    callback(err, isValid, { id: user.id, name: user.name }); 
}); 
}; 

server.auth.strategy(strategy_name, scheme_name, { validateFunc: validate }); 

你的权威性应该有像模式,范围,策略等选项

... 
... 
auth :{ 
    mode:'required', 
    strategy:'strategy_name', 
    scope: ['ADMIN', 'USER'] 
}, 
... 
... 

您可以使用Bell