hapi入门之Authentication篇
发布于 7 年前 作者 Zuckjet 3419 次浏览 来自 分享

Authentication

hapi里面的Authentication(验证)是基于scheme和strategies这两个概念的。 你可以把scheme理解为一个通用型的验证,是那种基础的,概要的的描述。 另一方面,strategy是一个预先配置的、命名的scheme实例。

为了更好地理解hapi中的Authentication,请看下面这个示例: ’’’ ‘use strict’;

const Bcrypt = require(‘bcrypt’); const Hapi = require(‘hapi’); const Basic = require(‘hapi-auth-basic’);

const server = new Hapi.Server(); server.connection({ port: 3000 });

const users = { john: { username: ‘john’, password: ‘$2a$10$iqJSHD.BGr0E2IxQwYgJmeP3NvhPrXAeLSaGCj6IR/XU5QtjVu5Tm’, // 'secret’ name: ‘John Doe’, id: ‘2133d32a’ } };

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.register(Basic, (err) => {

if (err) {
    throw err;
}

server.auth.strategy('simple', 'basic', { validateFunc: validate });
server.route({
    method: 'GET',
    path: '/',
    config: {
        auth: 'simple',
        handler: function (request, reply) {
            reply('hello, ' + request.auth.credentials.name);
        }
    }
});

server.start((err) => {

    if (err) {
        throw err;
    }

    console.log('server running at: ' + server.info.uri);
});

}); ’’’ 上述代码做了如下几个操作:

  1. 定义了一个用户数据信息,包括用户名、密码等信息。
  2. 定义了一个验证函数,它是针对于hapi-auth-basic具体实现的一个功能,允许我们去验证用户提供给我们的凭证。
  3. 注册了一个插件(hapi-auth-basic),该插件创建了一个命名为basic的scheme。

执行上述文件,访问localhost:3000。在弹出的登录框中输入用户名及密码,页面将展示:hello, John Doe tip:如果npm install bcrypt报错,可使用bcryptjs模块替代bcrypt,其余代码无需改变。

回到顶部