fastify 不使用jwt 使用cookie进行认证信息的管理

要在 Fastify 中使用 Cookie 进行认证信息管理,可以使用 fastify-cookie 插件来处理 Cookie。以下是一个示例,展示如何设置和读取 Cookie 以进行认证:

  1. 安装 fastify-cookie 插件:

    npm install fastify-cookie
  2. 设置 Fastify 服务器并配置 Cookie 插件:

    const fastify = require('fastify')({ logger: true });
    const fastifyCookie = require('fastify-cookie');

    // 注册 fastify-cookie 插件
    fastify.register(fastifyCookie, {
    secret: 'my-secret', // 用于签名 Cookie 的密钥
    parseOptions: {} // 可选的解析选项
    });

    // 登录路由,设置认证 Cookie
    fastify.post('/login', async (request, reply) => {
    const { username, password } = request.body;

    // 这里应该验证用户名和密码
    if (username === 'user' && password === 'pass') {
    // 设置 Cookie
    reply
    .setCookie('auth', 'authenticated', {
    path: '/',
    httpOnly: true, // 仅通过 HTTP(S) 传输,防止 XSS 攻击
    secure: process.env.NODE_ENV === 'production', // 仅在生产环境中使用 HTTPS
    maxAge: 3600 // Cookie 有效期为 1 小时
    })
    .send({ message: '登录成功' });
    } else {
    reply.status(401).send({ message: '用户名或密码错误' });
    }
    });

    // 受保护的路由,检查认证 Cookie
    fastify.get('/protected', async (request, reply) => {
    const { auth } = request.cookies;

    if (auth === 'authenticated') {
    reply.send({ message: '你已认证' });
    } else {
    reply.status(401).send({ message: '未认证' });
    }
    });

    // 启动服务器
    const start = async () => {
    try {
    await fastify.listen(3000);
    fastify.log.info(`服务器正在运行在 http://localhost:3000`);
    } catch (err) {
    fastify.log.error(err);
    process.exit(1);
    }
    };

    start();

 

在这个示例中:

  • /login 路由用于处理用户登录,并设置一个名为 auth 的 Cookie。
  • /protected 路由用于检查用户是否已认证,通过读取 auth Cookie 的值来判断。

确保在生产环境中使用 HTTPS 以确保 Cookie 的安全性。

posted on 2025-03-18 18:01  漫思  阅读(28)  评论(0)    收藏  举报

导航