Shubhashis Roy Dipta
Shubhashis Roy Dipta

Reputation: 157

FacebookTokenError: This authorization code has been used passport-js

I have implemented log in with facebook using passport.js. But sometimes whenever I try to log in, it gives me this error -

FacebookTokenError: This authorisation code has been used

But the fact is it's too random. Sometimes it works perfectly. Sometimes gives this error. I have tried all the solutions provided in the SO posts already. None of them works.

I am using react as my frontend and node.js as the backend. For session middleware using express-session.

Here is the code I used to implement log in with facebook

import passport from 'passport';
import { Strategy } from 'passport-facebook';

const { FACEBOOK_APP_ID, FACEBOOK_APP_SECRET, API_URL } = process.env;

export default (app) => {
  app.use(passport.initialize());
  app.use(passport.session());

  passport.serializeUser((user, cb) => cb(null, user));
  passport.deserializeUser((obj, cb) => cb(null, obj));

  passport.use(new Strategy({
    clientID: FACEBOOK_APP_ID,
    clientSecret: FACEBOOK_APP_SECRET,
    callbackURL: `${API_URL}facebook/callback`,
    profileFields: ['id', 'displayName', 'email', 'name', 'photos'],
    passReqToCallback: true,
    enableProof: true,

  }, async (req, accessToken, refreshToken, profile, cb) => {
    try {
      const email = (profile.emails && profile.emails[0].value) || '';
      const { displayName } = profile;
      const users = await Users.findOrCreate({
        where: { email },
        defaults: { name: displayName },
      }).catch((err) => {
        console.log(err);
      });
      if (users.length) {
        req.session.userId = users[0].get('id');
        return cb(null, users[0]);
      }
    } catch (err) {
      console.log('error during fb: ', err);
    }
    return cb('error in facebook');
  }));

  app.use('/facebook', passport.authenticate('facebook', { session: false, scope: ['public_profile', 'email'] }));

  app.use('/facebook/callback', passport.authenticate('facebook', { session: false, failureRedirect: `${FRONTEND_HOST}` }), (_, res) => {
    res.redirect(`${FRONTEND_HOST}`);
  });
};

This is the full error I get -

two muppets

Upvotes: 0

Views: 293

Answers (1)

Mahmudur Rahman
Mahmudur Rahman

Reputation: 678

I'm not sure about the actual problem with your code but you need to use:

app.get('/facebook', ...)
app.get('/facebook/callback', ...)

instead of

app.use(...)

Upvotes: 4

Related Questions