在 Web 开发中,用户身份验证是一个非常重要的功能。在 Hapi 框架中,我们可以使用 hapi-auth-cookie 插件来实现用户身份验证。
什么是 hapi-auth-cookie 插件?
hapi-auth-cookie 是 Hapi 框架的一个插件,它提供了一种基于 cookie 的用户身份验证机制。当用户登录时,服务器会将一个包含用户信息的 cookie 发送给客户端,客户端每次请求时都会带上这个 cookie,服务器通过验证这个 cookie 来确定用户的身份。
如何使用 hapi-auth-cookie 插件?
以下是使用 hapi-auth-cookie 插件进行用户身份验证的步骤:
1. 安装 hapi-auth-cookie 插件
在项目根目录下执行以下命令:
npm install hapi-auth-cookie
2. 注册插件
在 Hapi 服务器初始化时,使用 server.register 方法注册 hapi-auth-cookie 插件:
const Hapi = require('hapi');
const server = new Hapi.Server();
await server.register(require('hapi-auth-cookie'));3. 配置插件
在注册插件后,需要在服务器配置中设置插件的选项:
// www.javascriptcn.com code example
server.auth.strategy('session', 'cookie', {
cookie: {
name: 'sid-example',
password: 'password-should-be-32-characters',
isSecure: false
},
redirectTo: '/login',
validateFunc: async (request, session) => {
const account = await Account.findById(session.id);
if (!account) {
return { valid: false };
}
return { valid: true, credentials: account };
}
});上面的代码中,我们使用 server.auth.strategy 方法来定义一个名为 session 的认证策略,它使用 cookie 作为认证方式。其中,cookie 选项用于设置 cookie 的相关配置,比如 cookie 的名称、加密密码和是否启用 HTTPS 等。redirectTo 选项用于设置用户未登录时需要跳转的页面。validateFunc 选项用于设置验证函数,它会在每次请求时被调用,用于验证 cookie 是否有效。
4. 应用认证策略
在需要进行身份验证的路由中,使用 config.auth 属性来应用认证策略:
// www.javascriptcn.com code example
server.route({
method: 'GET',
path: '/profile',
config: {
auth: 'session',
handler: (request, h) => {
return `Welcome ${request.auth.credentials.username}!`;
}
}
});上面的代码中,我们定义了一个 /profile 路由,它需要进行身份验证,使用的认证策略是 session。在处理函数中,我们可以通过 request.auth.credentials 属性来获取用户信息。
示例代码
以下是一个完整的示例代码,它演示了如何使用 hapi-auth-cookie 插件进行用户身份验证:
// www.javascriptcn.com code example
const Hapi = require('hapi');
const server = new Hapi.Server();
const users = [
{ id: 1, username: 'admin', password: 'admin' },
{ id: 2, username: 'user', password: 'user' }
];
const validate = async (request, username, password) => {
const user = users.find(u => u.username === username && u.password === password);
if (!user) {
return { credentials: null, isValid: false };
}
return { credentials: user, isValid: true };
};
const init = async () => {
await server.register(require('hapi-auth-cookie'));
server.auth.strategy('session', 'cookie', {
cookie: {
name: 'sid-example',
password: 'password-should-be-32-characters',
isSecure: false
},
redirectTo: '/login',
validateFunc: validate
});
server.route([
{
method: 'GET',
path: '/',
config: {
auth: false,
handler: (request, h) => {
return 'Hello world!';
}
}
},
{
method: 'GET',
path: '/profile',
config: {
auth: 'session',
handler: (request, h) => {
return `Welcome ${request.auth.credentials.username}!`;
}
}
},
{
method: 'GET',
path: '/login',
config: {
auth: false,
handler: (request, h) => {
return `
<form method="post" action="/login">
<input type="text" name="username">
<input type="password" name="password">
<button type="submit">Login</button>
</form>
`;
}
}
},
{
method: 'POST',
path: '/login',
config: {
auth: false,
handler: (request, h) => {
const { username, password } = request.payload;
request.cookieAuth.set({ username, password });
return h.redirect('/profile');
}
}
}
]);
await server.start();
};
init().catch(console.error);在上面的示例代码中,我们定义了一个 /login 路由,它包含一个登录表单。当用户提交表单时,会将用户名和密码保存到 cookie 中,并跳转到 /profile 路由。在 /profile 路由中,我们使用 request.auth.credentials 属性来获取用户信息,并根据用户信息来生成欢迎消息。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67d2ace7a941bf713452d476