创建一个auth.js中间件
我已经创建了一个具有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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于在Fastify中使用JWT身份验证工作的任何其他人,Fastify都有一个很好的插件来支持它:
用于使用JWT身份验证的您可以创建一个插件来使用
authenticate
这样的插件:然后,您可以使用它从任何路线中,您都想对用户进行身份验证:
更好地在生命周期(例如OnRequest)上进行身份验证,以防止在处理请求的主体时进行DOS攻击。
如果您使用的是打字稿,则可能需要扩展快速类型。您可以这样做:
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:Then, you can use it from any route you would like to authenticate the user like this:
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:
您可以将您的auth函数添加为
prehandler
hook of this:或类似:
查看您的代码,我尚不完全清楚它是否代表多个文件或确切的情况。您可能需要将其分解为带有文件名的单独的代码块,以澄清您的问题。
You can add your auth function as a
preHandler
hook like this:or like this:
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.