Api Nodejs jwt-Simple

0

I'm putting together an api with nodejs, and I want to include the token with jwt-simple, I can create token and use it to access the routes, but when you want to check the token expiration directly it jumps through the 'invalid token' error cath ' How can I solve it?

App.js

router.get("/Producto/:id",auth,(req,res)=>{ ProductoModel.findById(req.params.id).populate('Iddetalle').exec((err,respuesta)=>{ if(err) res.send({estado:{codigo:0,respuesta:err.message}}); res.send({estado:{codigo:0,respuesta:'Operacion Buscar exitosa '}, Producto:respuesta}); console.log('Operacion Buscar exitosa'); }) });

auth.js

'use strict'
var service = require('../service');


function isAuth(req,res, next){

    if(!req.headers.authorization){
        return res.status(403).send({message:'No tienes autorización'});
    }
    var token=req.headers.authorization.split(" ")[1];
    service.decodeToken(token).then(response=>{
        req.user=response;
        next();
    }).catch(reject=>{
        res.status(reject.status).send({message:reject.message})
        next();
    })
}

module.exports= isAuth;

service.js

var jwt = require('jwt-simple');
var moment = require('moment');
var config = require('../config');

function CrearToken(estudianteModel){
    var payload = {
        sub:estudianteModel._id,
        Nombre:estudianteModel.Nombre,
        Apellido:estudianteModel.Apellido,
        Legajo:estudianteModel.Legajo,
        Password:estudianteModel.Password,
        IdCarrera:estudianteModel.IdCarrera,
        iat:moment().unix(),
        exp: moment().add(2,"minutes").unix()
     };
     return jwt.encode(payload,config.SECRET_TOKEN) 
}

function decodeToken(token){
    var decode=new Promise((resolve,reject)=>{
        try {
            var payload=jwt.decode(token,config.SECRET_TOKEN);
            if(payload.exp<=moment().unix()){
                reject({
                    status:401,
                    message:'Token Expirado'
                });
            }
            else{
            console.log('payload.sub', payload.sub);
            resolve(payload.sub);}
        } catch (error) {
            console.log(error);
            reject({
                status:501,
                message:'invalid token'
            });
        }
    })
    console.log('defen:', decode);
    return decode;
}

module.exports= {CrearToken,decodeToken}
    
asked by Federico 20.10.2018 в 01:19
source

1 answer

0

According to your code, the value you give to the expiration is a Unix timestamp and the formats accepted by the 'expireIn' property must be expressed with the number of seconds or a string describing a time interval 'zeit / ms'

  

expiresIn: expressed in seconds or a string that describes a time interval zeit / ms.   For example: 60, "2 days", "10h", "7d". A numeric value is interpreted as a count of seconds. If you use a string, be sure to provide the units of time (days, hours, etc.), otherwise the millisecond unit is used by default ("120" equals "120ms").

Source: link

I hope this solves your mistake.

Greetings

    
answered by 15.11.2018 в 21:24