jaredhanson / passport

Simple, unobtrusive authentication for Node.js.
https://www.passportjs.org?utm_source=github&utm_medium=referral&utm_campaign=passport&utm_content=about
MIT License
22.94k stars 1.24k forks source link

TokenError: Code is invalid or expired #974

Open xonarin opened 1 year ago

xonarin commented 1 year ago

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

xonarin commented 1 year ago

How to handle TokenError ?

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

YasharF commented 1 year ago

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