创建令牌后我应该在哪里设置授权标头?

发布于 2025-01-09 12:44:45 字数 1200 浏览 0 评论 0原文

我正在尝试实现一个基于代币的安全系统。问题是我不知道创建授权标头后必须在哪里设置它才能在所有不同的路由中检查它。我的代码是下一个。 我想不使用邮递员或任何类似的程序来做到这一点。

这是用户登录的路由,我在其中创建令牌

router.post('/login',(req,res)=>{
    const user = req.body.user;
    const token = jwt.sign({user},'secret_key');// generamos un identificador para el usuario que acaba de registrarse
    res.json({
        token
    });
}); 

然后,我有这个路由来测试它的工作原理

router.get('/protected',ensureToken,(req,res)=>{
    jwt.verify(req.token,'secret_key',(err,data)=>{
        if(err){
            res.sendStatus(403);
        }else{
            res.json({
                text:'protected'
            });
        }
    });
});

最后,这是中间件

function ensureToken(req,res,next){
    const bearerHeader = req.headers['authorization'];
    console.log(bearerHeader);
    if(typeof bearerHeader != 'undefined'){
        const bearer = bearerHeader.split(" ");
        const bearerToken= bearer[1];
        req.token = bearerToken; //almacenamos el token en el objeto de la peticion
        next();
    }else{
        res.sendStatus(403);//status de no permitido
    }
}

我应该在其中为所有路由类型设置授权标头“get”作为受保护的路由?

I am triying to implement a securuty system based on tokens. The problem is that I dont know where I must set the authorization header after create it in order to check it in all of my diferent routes. My code is the next.
I want to do it WITHOUT USING POSTMAN or any program like that.

This is the route for user login, where I create the token

router.post('/login',(req,res)=>{
    const user = req.body.user;
    const token = jwt.sign({user},'secret_key');// generamos un identificador para el usuario que acaba de registrarse
    res.json({
        token
    });
}); 

Then, I have this route to test it works

router.get('/protected',ensureToken,(req,res)=>{
    jwt.verify(req.token,'secret_key',(err,data)=>{
        if(err){
            res.sendStatus(403);
        }else{
            res.json({
                text:'protected'
            });
        }
    });
});

And finally, this is the middleware

function ensureToken(req,res,next){
    const bearerHeader = req.headers['authorization'];
    console.log(bearerHeader);
    if(typeof bearerHeader != 'undefined'){
        const bearer = bearerHeader.split(" ");
        const bearerToken= bearer[1];
        req.token = bearerToken; //almacenamos el token en el objeto de la peticion
        next();
    }else{
        res.sendStatus(403);//status de no permitido
    }
}

Where I should set the authorization header for all of my routes type 'get' as the protected route?

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

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

发布评论

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

评论(1

治碍 2025-01-16 12:44:45

验证

router.get('/verify', async (req, res, next) => {
    try {
        const token = req.headers['x-access-token']//client should this value

        if (!token){
            return res.status(401).send({
                success: false,
                message: 'Unauthorized request',
            })
        }
        else if (isExpiredToken(token)){
            return res.status(300).send({
                success: false,
                message: 'Token is expired',
            })
        }

        const decoded = jwt.verify(token, SECRET_KEY)

        const expiredAt = moment.unix(decoded.exp).subtract(@YOUR_EXPIRED_TIME, 'minutes')
        const now = moment()

        let newToken = null

        if (now.isAfter(expiredAt)) {//refresh the token
            const userFromDB = await User.findOne({
                where: {
                    id: decoded.id,
                },
            })

            const content = util.sanitize(userFromDB)

            newToken = await jwt.sign(content, SECRET_KEY, {
                audience: content.email,
                issuer: 'YOUR_APP',
                expiresIn: 'YOUR_EXPIRED_TIME',
            })

            console.log(
                `VERIFY\tToken refreshed automatically for user-${content.id}`
            )
        }

        res.send({
            success: true,
            nextToken: newToken,
        })
    } catch (e) {
        console.log(e)

        res.status(500).send({
            success: false,
            message: 'Internal server error',
        })
    }
})

中间件

 async function authMiddleware(req, res, next){
   /* In this case, user can authenticate with header['x-access-token'] or body['accessToken']*/
   const token = req.header['x-access-token'] || req.body['accessToken'] || undefined

   if(!token) return res.status(401).send({ success: false, message: 'unauthorized' })

   try{
     const user = await jwt.verify(token, secret)
     req.user = { ...user }
     return next()
   }
   catch(e){
     console.log(e)
     return res.status(500).send({ success : false, message : 'internal server error' })
    }
}

Verifying

router.get('/verify', async (req, res, next) => {
    try {
        const token = req.headers['x-access-token']//client should this value

        if (!token){
            return res.status(401).send({
                success: false,
                message: 'Unauthorized request',
            })
        }
        else if (isExpiredToken(token)){
            return res.status(300).send({
                success: false,
                message: 'Token is expired',
            })
        }

        const decoded = jwt.verify(token, SECRET_KEY)

        const expiredAt = moment.unix(decoded.exp).subtract(@YOUR_EXPIRED_TIME, 'minutes')
        const now = moment()

        let newToken = null

        if (now.isAfter(expiredAt)) {//refresh the token
            const userFromDB = await User.findOne({
                where: {
                    id: decoded.id,
                },
            })

            const content = util.sanitize(userFromDB)

            newToken = await jwt.sign(content, SECRET_KEY, {
                audience: content.email,
                issuer: 'YOUR_APP',
                expiresIn: 'YOUR_EXPIRED_TIME',
            })

            console.log(
                `VERIFY\tToken refreshed automatically for user-${content.id}`
            )
        }

        res.send({
            success: true,
            nextToken: newToken,
        })
    } catch (e) {
        console.log(e)

        res.status(500).send({
            success: false,
            message: 'Internal server error',
        })
    }
})

Middleware

 async function authMiddleware(req, res, next){
   /* In this case, user can authenticate with header['x-access-token'] or body['accessToken']*/
   const token = req.header['x-access-token'] || req.body['accessToken'] || undefined

   if(!token) return res.status(401).send({ success: false, message: 'unauthorized' })

   try{
     const user = await jwt.verify(token, secret)
     req.user = { ...user }
     return next()
   }
   catch(e){
     console.log(e)
     return res.status(500).send({ success : false, message : 'internal server error' })
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文