Node Js 将角色作为字符串传递给 JWT 验证函数

发布于 2025-01-10 05:51:00 字数 1185 浏览 0 评论 0原文

JWT 验证函数接受 req、res 和 next 作为其参数。我需要传递一个额外的字符串“Admin”,以便只有管理员用户可以访问此 API

我的 jwtVerification.js 代码:

module.exports = async function (req, res, next) { //I need to be able to add role to this call
    try {       
        const token = req.header("Authorization");

        if (!token) return res.status(401).send('Invalid access token.');

        const _token = token.substring(7, token.length);

        const decoded = jwt.verify(_token, process.env.JWT_PRIVATE_KEY)

        const user = await prisma.user.findFirst({ where: { id: decoded.id } });

        if (!user) return res.status(401).send('Invalid access token.');
     
        //I need to be able to read the role so that I can do the following verifications
        //if(!role) next();
        //else{
        //   if(user.role !== role || decode.role !== role) return res.status(403).send('Forbidden!')
        //   else next();
        //}
        next();

    } catch (error) {
        res.status(401).send(error.message);
    }
};

最后,API 调用本身: //例如使用verifyJWT('Admin')

router.post('/test', verifyJWT, async (req, res) => {
    res.send('hi');
})

the JWT verification function accepts the req, res and next as its params. I need to pass an additional string 'Admin' so that only admin users may access this API

My jwtVerification.js code:

module.exports = async function (req, res, next) { //I need to be able to add role to this call
    try {       
        const token = req.header("Authorization");

        if (!token) return res.status(401).send('Invalid access token.');

        const _token = token.substring(7, token.length);

        const decoded = jwt.verify(_token, process.env.JWT_PRIVATE_KEY)

        const user = await prisma.user.findFirst({ where: { id: decoded.id } });

        if (!user) return res.status(401).send('Invalid access token.');
     
        //I need to be able to read the role so that I can do the following verifications
        //if(!role) next();
        //else{
        //   if(user.role !== role || decode.role !== role) return res.status(403).send('Forbidden!')
        //   else next();
        //}
        next();

    } catch (error) {
        res.status(401).send(error.message);
    }
};

finally, the API call itself:
//use verifyJWT('Admin') for example

router.post('/test', verifyJWT, async (req, res) => {
    res.send('hi');
})

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

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

发布评论

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

评论(1

三五鸿雁 2025-01-17 05:51:00

你可以使用这样的东西:

module.exports = function (myParam) => {
    
         return async function (req, res, next) { 
            //use myParam here
            try {       
                const token = req.header("Authorization");

                if (!token) return res.status(401).send('Invalid access token.');

                const _token = token.substring(7, token.length);

                const decoded = jwt.verify(_token, process.env.JWT_PRIVATE_KEY)

                const user = await prisma.user.findFirst({ where: { id: decoded.id } });

                if (!user) return res.status(401).send('Invalid access token.');
             
                //I need to be able to read the role so that I can do the following verifications
                //if(!role) next();
                //else{
                //   if(user.role !== role || decode.role !== role) return res.status(403).send('Forbidden!')
                //}
                next();

            } catch (error) {
                res.status(401).send(error.message);
            }
    }
};

然后以这种方式使用中间件:

router.post('/test', verifyJWT(someParam), async (req, res) => {
    res.send('hi');
})

You cat use some thing like this:

module.exports = function (myParam) => {
    
         return async function (req, res, next) { 
            //use myParam here
            try {       
                const token = req.header("Authorization");

                if (!token) return res.status(401).send('Invalid access token.');

                const _token = token.substring(7, token.length);

                const decoded = jwt.verify(_token, process.env.JWT_PRIVATE_KEY)

                const user = await prisma.user.findFirst({ where: { id: decoded.id } });

                if (!user) return res.status(401).send('Invalid access token.');
             
                //I need to be able to read the role so that I can do the following verifications
                //if(!role) next();
                //else{
                //   if(user.role !== role || decode.role !== role) return res.status(403).send('Forbidden!')
                //}
                next();

            } catch (error) {
                res.status(401).send(error.message);
            }
    }
};

And after that use the middleware this way:

router.post('/test', verifyJWT(someParam), async (req, res) => {
    res.send('hi');
})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文