hapi-auth-cookie
hapi中身份验证的一种官方认证插件
Cookie身份验证提供了简单的基于cookie的会话管理。用户必须通过其他手段(通常是web表单)进行身份验证,在成功身份验证后,浏览器接收到带有会话cookie的回复。cookie使用Iron对会话内容进行加密和签名。如果cookie的加密内容需要对每个请求进行验证,则包含会话cookie的后续请求将通过提供的validateFunc进行身份验证和验证。
官方例子 + api标注 + hapi17版本
const Hapi = require('hapi');
const internals = {};
let uuid = 1; // 仅测试不是一个标准的事例
// 模拟数据库, 在users内查找用户名
const users = {
john: {
id: 'john',
password: 'password',
name: 'John Doe'
}
};
const login = async (request, h) => {
if (request.auth.isAuthenticated) {
return h.redirect('/');
}
let message = '';
let account = null;
if (request.method === 'post') {
if (!request.payload.username ||
!request.payload.password) {
message = 'Missing username or password';
}
else {
account = users[request.payload.username];
if (!account ||
account.password !== request.payload.password) {
message = 'Invalid username or password';
}
}
}
if (request.method === 'get' || message) {
return '<html><head><title>Login page</title></head><body>' +
(message ? '<h3>' + message + '</h3><br/>' : '') +
'<form method="post" action="/login">' +
'Username: <input type="text" name="username"><br>' +
'Password: <input type="password" name="password"><br/>' +
'<input type="submit" value="Login"></form></body></html>';
}
const sid = String(++uuid);
await request.server.app.cache.set(sid, { account }, 0);
// 必须在成功登录后调用才能开始会话。会话必须是非空对象,它基于request.auth.credentials中的成功后续身份验证进行设置
request.cookieAuth.set({ sid });
return h.redirect('/');
};
const home = (request, h) => {
return '<html><head><title>Login page</title></head><body><h3>Welcome ' +
request.auth.credentials.name +
'!</h3><br/><form method="get" action="/logout">' +
'<input type="submit" value="Logout">' +
'</form></body></html>';
};
const server = Hapi.server({ port: 8000 });
exports.start = async () => {
await server.register(require('../'));
const cache = server.cache({ segment: 'sessions', expiresIn: 3 * 24 * 60 * 60 * 1000 }); // ttl-以毫秒为单位设置cookie过期时间
server.app.cache = cache;
server.auth.strategy('session', 'cookie', {
password: 'password-should-be-32-characters', // cookie编码。应该至少有32个字符长。
cookie: 'sid-example', // 默认名字
redirectTo: '/login', // 可选的登录URI或函数(请求),返回URI以将未经身份验证的请求重定向。注意,它只会在“必需”身份验证模式时触发。要启用或禁用特定路由的重定向,请设置路由插件
isSecure: false, // 则允许通过不安全的连接传输cookie 默认true
validateFunc: async (request, session) => { // 一个可选的会话验证函数,用于验证每个请求的会话cookie的内容。
const cached = await cache.get(session.sid);
const out = {
valid: !!cached
};
if (out.valid) {
out.credentials = cached.account;
}
return out;
}
});
server.auth.default('session');
server.route([
{
method: 'GET',
path: '/',
handler: home,
},
{
method: ['GET', 'POST'],
path: '/login',
handler: login,
options: {
auth: { mode: 'try' }
}
}
]);
await server.start();
console.log(`Server started at: ${server.info.uri}`);
};
internals.start = async function () {
try {
await exports.start();
}
catch (err) {
console.error(err.stack);
process.exit(1);
}
};
internals.start();
hapi-auth-cookie 常与表单连用
先直接在浏览器调用下
http请求302 表示重定向到login
对应的代码行
// request.auth.isAuthenticated 是否通过验证 true false
if (request.auth.isAuthenticated) {
return h.redirect('/');
}
换环境 直接在浏览器进入 跳转login - 输入账号密码 - wlcome john Doe
是ok的
使用场景
结合Bell实现第三方身份验证
溜了~