jaredhanson / passport

Simple, unobtrusive authentication for Node.js.

Home Page:https://www.passportjs.org?utm_source=github&utm_medium=referral&utm_campaign=passport&utm_content=about

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

TokenError: Code is invalid or expired

xonarin opened this issue · comments

Hello.

I use authorization method - https://www.passportjs.org/packages/passport-vkontakte/

And authorization works for me, but sometimes an error pops up and the application crashes.

What could be the problem? Here is the code.


app.get(
    '/auth/vk',
    (_0, res, next) => {
        const now = Date.now();

        if (now - lastVkAuth < 1000) {
            res.redirect('/');
        } else {
            lastVkAuth = Date.now();
            next();
        }
    },
    passport.authenticate('vkontakte', {
        failureRedirect: '/',
        session: false,
    }),
);

app.get(
    '/auth/vk/return',
    passport.authenticate('vkontakte', {
        failureRedirect: '/',
        session: false,
    }),
    async (req, res) => {
        if (req.user && req.authInfo) {
            const expiresIn = 60 * 60 * 24 * 180; // 180 days
            const token = jwt.sign(req.user, config.auth.jwt.secret, { expiresIn });
            res.cookie(config.auth.tokenKey, token, { maxAge: 1000 * expiresIn });

            // Set referrer if it is define in cookies
            const { refId } = req.cookies;
            if (refId && req.authInfo.isRegistered) {
                await repositories.users.setReferrer(req.user.id, refId);
                res.clearCookie('refId');
            }
        }
        res.redirect('/');
    },
);

Error screen - https://ibb.co/mJB1JsY

How to handle TokenError ?

Passing err to the argument and the if(err) condition didn't help anywhere.

It sounds like your token is just expiring. You would need to refresh it with something like passport-oauth2-refresh.