创建一个auth.js中间件

发布于 2025-01-24 04:23:54 字数 731 浏览 4 评论 0原文

我已经创建了一个具有Fastify和Prisma的auth.js中间件,但我不知道如何将其插入我的路线。这里有一些例子

const jwt = require("jsonwebtoken");
require("dotenv").config();

module.exports = (request, reply) => {
  try {
    const token = request.headers.authorization.split(" ")[1];
    const decodedToken = jwt.verify(token, process.env.SECRET_TOKEN);
    request.token = decodedToken;
  } catch (error) {
    reply.status(401).send({
      message: "Vous êtes pas authentifié",
    });
  }
};
const profilCtrl = require("../../controller/user");

const auth = require("../../middleware/auth");
async function routes(fastify) {
  fastify.get("/profil/:id", profilCtrl.profile);
}

module.exports = routes;

I have created an auth.js middleware with fastify and prisma but I don't know how to insert it in my route. Here are some examples

const jwt = require("jsonwebtoken");
require("dotenv").config();

module.exports = (request, reply) => {
  try {
    const token = request.headers.authorization.split(" ")[1];
    const decodedToken = jwt.verify(token, process.env.SECRET_TOKEN);
    request.token = decodedToken;
  } catch (error) {
    reply.status(401).send({
      message: "Vous êtes pas authentifié",
    });
  }
};
const profilCtrl = require("../../controller/user");

const auth = require("../../middleware/auth");
async function routes(fastify) {
  fastify.get("/profil/:id", profilCtrl.profile);
}

module.exports = routes;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

掀纱窥君容 2025-01-31 04:23:54

对于在Fastify中使用JWT身份验证工作的任何其他人,Fastify都有一个很好的插件来支持它:

用于使用JWT身份验证的您可以创建一个插件来使用authenticate这样的插件:

import fastifyPlugin from 'fastify-plugin';
import fastifyJwt, { FastifyJWTOptions } from '@fastify/jwt';
import { FastifyRequest, FastifyReply } from 'fastify';

export default fastifyPlugin<FastifyJWTOptions>(async (fastify) => {
    fastify.register(fastifyJwt, {
        secret: '',
        decode: { complete: true },
        sign: { algorithm: 'RS256', expiresIn: '1h' },
        decoratorName: 'jwtUser',
    });

    fastify.decorate(
        'authenticate',
        async (request: FastifyRequest, reply: FastifyReply) => {
            try {
                await request.jwtVerify();
            } catch (error) {
                throw fastify.httpErrors.unauthorized();
            }
        }
    );
});

然后,您可以使用它从任何路线中,您都想对用户进行身份验证:

import { FastifyPluginAsync } from 'fastify';

const root: FastifyPluginAsync = async (fastify, opts): Promise<void> => {
    fastify.get(
        '/',
        {
            schema: {},
            onRequest: [fastify.authenticate],
        },
        (request, reply) => {
            return reply.code(200).send('Welcome!')
        }
    );
};

export default root;

更好地在生命周期(例如OnRequest)上进行身份验证,以防止在处理请求的主体时进行DOS攻击。

如果您使用的是打字稿,则可能需要扩展快速类型。您可以这样做:

import 'fastify';
import { FastifyRequest, FastifyReply } from 'fastify';
declare module 'fastify' {

    /**
     * Type function to extend FastifyInstance to work with hook authentication
     * onRequest: [fastify.authenticate] defined at src\plugins\jwtVerification.ts
     */
    type Authenticate = (
        request: FastifyRequest,
        reply: FastifyReply
    ) => Promise<void>;

    /** Apply the extension */
    interface FastifyInstance {
        authenticate: Authenticate;
    }
}

For anyone else working with JWT authentication in Fastify, fastify has a great plugin to support it:

For authentication with JWT you can create a plugin to decorate the fastify instance with authenticate like this:

import fastifyPlugin from 'fastify-plugin';
import fastifyJwt, { FastifyJWTOptions } from '@fastify/jwt';
import { FastifyRequest, FastifyReply } from 'fastify';

export default fastifyPlugin<FastifyJWTOptions>(async (fastify) => {
    fastify.register(fastifyJwt, {
        secret: '',
        decode: { complete: true },
        sign: { algorithm: 'RS256', expiresIn: '1h' },
        decoratorName: 'jwtUser',
    });

    fastify.decorate(
        'authenticate',
        async (request: FastifyRequest, reply: FastifyReply) => {
            try {
                await request.jwtVerify();
            } catch (error) {
                throw fastify.httpErrors.unauthorized();
            }
        }
    );
});

Then, you can use it from any route you would like to authenticate the user like this:

import { FastifyPluginAsync } from 'fastify';

const root: FastifyPluginAsync = async (fastify, opts): Promise<void> => {
    fastify.get(
        '/',
        {
            schema: {},
            onRequest: [fastify.authenticate],
        },
        (request, reply) => {
            return reply.code(200).send('Welcome!')
        }
    );
};

export default root;

Authentication is better done earlier on the lifecycle, like onRequest, to prevent DOS attacks when the body of the request is processed.

If you are using Typescript, you might need to extend Fastify types. You can do it like this:

import 'fastify';
import { FastifyRequest, FastifyReply } from 'fastify';
declare module 'fastify' {

    /**
     * Type function to extend FastifyInstance to work with hook authentication
     * onRequest: [fastify.authenticate] defined at src\plugins\jwtVerification.ts
     */
    type Authenticate = (
        request: FastifyRequest,
        reply: FastifyReply
    ) => Promise<void>;

    /** Apply the extension */
    interface FastifyInstance {
        authenticate: Authenticate;
    }
}
瀟灑尐姊 2025-01-31 04:23:54

您可以将您的auth函数添加为prehandler hook of this:

fastify.addHook('preHandler', (request, reply, done) => {
  // some code
  done()
})

或类似:

fastify.route({
  method: 'GET',
  url: '/profil/:id',
  preHandler: fastify.auth([fastify.yourMiddleware]),
  handler: (req, reply) => { ... }
})

查看您的代码,我尚不完全清楚它是否代表多个文件或确切的情况。您可能需要将其分解为带有文件名的单独的代码块,以澄清您的问题。

You can add your auth function as a preHandler hook like this:

fastify.addHook('preHandler', (request, reply, done) => {
  // some code
  done()
})

or like this:

fastify.route({
  method: 'GET',
  url: '/profil/:id',
  preHandler: fastify.auth([fastify.yourMiddleware]),
  handler: (req, reply) => { ... }
})

Looking at your code I'm not totally clear on if it represents multiple files or what exactly is going on. You might want to break it up into separate blocks of code with file names to clarify your question.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文