Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

161
Views
Where should I set the authorization header after create the token?

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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' })
    }
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!