Monday, 15 May 2017

Where to control the expireIn JWT

I am building a client-server aplication using android, nodeJS and postgreSQL(sequelize), i already am able to do a simple login and registration, but i want to save sessions so i did this:

router.post('/login', function (req, res, next) {
if (JSON.stringify(req.body) == "{}") {
    return res.status(400).json({ Error: "Login request body is empty" });
}
if (!req.body.username || !req.body.password) {
    return res.status(400).json({ Error: "Missing fields for login" });
}

// search a user to login
User.findOne({ where: { username: req.body.username } }) // searching a user with the same username and password sended in req.body
    .then(function (user) {
        if (user && user.validPassword(req.body.password)) {
            //return res.status(200).json({ message: "loged in!" }); // username and password match


            var payload = { user: user };

            // create a token
            var token = jwt.sign(payload, 'superSecret', {
                expiresIn: 60 * 60 * 24
            });


            // return the information including token as JSON
            res.json({
                success: true,
                message: 'Enjoy your token!',
                token: token
            });

        }
        else {
            return res.status(401).json({ message: "Unauthorized" }); // if there is no user with specific fields send
        }
    }).catch(function (err) {
        console.error(err.stack)
        return res.status(500).json({ message: "server issues when trying to login!" }); // server problems
    });

});

as you guys can see i return the token to the client when login is sucess, in the client side i save the token on the SharedPreferences.

My daubt is that the token has a expiration time, so how can i control the expiration time of the token, should i control it on the server side, or on the client?

any tip is useful. Thanks



via Cris dois

No comments:

Post a Comment