Search code examples
node.jsaccess-tokenloopbackjs

Sliding expiration for access token with Loopback


I've installed Loopback and enabled ACL for a couple of models. I noticed that the Access Token is valid for ever, I would like to change this period somehow to, for example, an hour. But even better would be to reset this period when activity occurs (sliding expiration)

I've checked the documentation but couldn't fine anything about this subject. Any help/guidance would be appreciated!


Solution

  • When you call the login method you can specify a ttl property in seconds(I believe by default it's 2 weeks if you don't specify). Then you can have sliding expiration by having the following middleware:

    app.use(loopback.token()); // You should have this already
    app.use(function(req, res, next) {
        // Make sure this middleware is registered after loopback.token
        var token = req.accessToken;
        if (!token) {
            return next();
        }
        var now = new Date();
        if ( now.getTime() - token.created.getTime() < 1000 ) {
            return next();
        }
        req.accessToken.created = now;
        req.accessToken.ttl     = 604800; //one week
        req.accessToken.save(next);
    });