hapi裏面的Authentication(驗證)是基於scheme和strategies這兩個概念的。
你能夠把scheme理解爲一個通用型的驗證,是那種基礎的,概要的的描述。
另外一方面,strategy是一個預先配置的、命名的scheme實例。npm
爲了更好地理解hapi中的Authentication,請看下面這個示例:api
'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,其他代碼無需改變。ui