hapi入门之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);
    });
});

上述代码做了以下几个操纵:

定义了一个用户数据信息,包含用户名、暗码等信息。
定义了一个考证函数,它是针对于hapi-auth-basic详细完成的一个功用,许可我们去考证用户提供给我们的凭据。
注册了一个插件(hapi-auth-basic),该插件创建了一个定名为basic的scheme。
实行上述文件,接见localhost:3000。在弹出的登录框中输入用户名及暗码,页面将展现:hello, John Doe
tip:假如npm install bcrypt报错,可运用bcryptjs模块替换bcrypt,其他代码无需转变。

    原文作者:唐僧洗头爱飘柔
    原文地址: https://segmentfault.com/a/1190000009123089
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞