Passport-facebook FacebookTokenError: The provided authorization code has already been used

This block of code is related to passport.js implementation.

var FacebookStrategy = require('passport-facebook').Strategy;


var User = require('./app/models/users');
var config = require('./config');

module.exports = function (passport) {


    passport.serializeUser(function (user, done) {
        done(null, user.id);
    });

    passport.deserializeUser(function (id, done) {
        User.findById(id, function (err, user) {
            done(err, user);
        });
    });



    passport.use(new FacebookStrategy({
            clientID: config.facebook.appId,
            clientSecret: config.facebook.appSecret,
            callbackURL: config.facebook.redirectUrl,
            profileFields: ['id', 'name', 'displayName', 'emails', 'photos']

        },
        function (accessToken, refreshToken, profile, done) {
            process.nextTick(function () {

                User.findOne({'facebook.id': profile.id}, function (err, user) {

                        console.log(profile);

                    if (err) {
                        // console.log("tick errr");
                        return done(err)
                    }
                    ;
                    if (user)
                        return done(null, user);
                    else {
                        var newUser = new User();
                        newUser.facebook.id = profile.id;
                        newUser.facebook.token = accessToken;
                        newUser.facebook.name = profile.displayName;
                        newUser.facebook.email = profile.emails[0].value;
                        newUser.facebook.picurl = profile.photos[0].value;
                        // console.log("access token is "+accessToken);
                        //console.log(newUser.facebook.id);

                        newUser.save(function (err) {
                            if (err)
                                console.log(err);
                            return done(null, newUser);
                        })
                    }
                });
                });
            // done(null, profile);
        }
    ));

This part relates to api.js configuration.

 api.get('/auth/facebook', function (req, res, next) {

        passport.authenticate('facebook', {scope: ['email']})(req, res, next);
    });


    api.get('/auth/facebook/callback',

        passport.authenticate('facebook', {


            successRedirect: '#/home',
            failureRedirect: '#/login'


        })

    );


    };

I am encountering an issue while using Facebook login feature. The specific error message I am seeing is as follows:

FacebookTokenError: This authorization code has been used.
   at Strategy.parseErrorResponse (c:\Users\chetan kanjani\WebstormProjects\letsgo\node_modules\passport-facebook\lib\strategy.js:199:12)
   at Strategy.OAuth2Strategy._createOAuthError (c:\Users\chetan kanjani\WebstormProjects\letsgo\node_modules\passport-facebook\node_modules\passport-oauth2\lib\strategy.js:345:16)
   at c:\Users\chetan kanjani\WebstormProjects\letsgo\node_modules\passport-facebook\node_modules\passport-oauth2\lib\strategy.js:171:43
   at c:\Users\chetan kanjani\WebstormProjects\letsgo\node_modules\passport-facebook\node_modules\passport-oauth2\node_modules\oauth\lib\oauth2.js:177:18
   at passBackControl (c:\Users\chetan kanjani\WebstormProjects\letsgo\node_modules\passport-facebook\node_modules\passport-oauth2\node_modules\oauth\lib\oauth2.js:123:9)
   at IncomingMessage.<anonymous> (c:\Users\chetan kanjani\WebstormProjects\letsgo\node_modules\passport-facebook\node_modules\passport-oauth2\node_modules\oauth\lib\oauth2.js:143:7)
   at IncomingMessage.emit (events.js:129:20)
   at _stream_readable.js:908:16
   at process._tickDomainCallback (node.js:381:11)

Despite the mentioned error, the data fetched from Facebook still gets stored in the database successfully; I suspect there might be an issue with the auth/facebook/callback functionality.

The content of users.js file can be seen below:

var UserSchema = mongoose.Schema({
    local: {

        name: String,
        username: {type: String, index: {unique: true}},
        password: {type: String, select: false}
    },
    facebook: {
        id: String,
        token: String,
        email: String,
        name: String,
        picurl: String,
    },
    favouriteid: [{eventid: String}]

});


UserSchema.pre('save', function(next) {

    var user = this;


    if (!user.isModified('local.password')) return next();

    bcrypt.hash(user.local.password, null, null, function (err, hash) {
        if(err) return next(err);

        user.local.password = hash;
        next();

    });
});

UserSchema.methods.comparePassword = function(password) {

    var user = this;

    var a = bcrypt.compareSync(password, user.local.password);

    if (a == true)
        return true;
    else {
        console.log('error in compare password');
        return false;
    }

}

Answer №1

This issue occurs when you have left Apps login data in your Facebook account. To resolve this error, simply delete the login data related to the app.

  1. Sign in to your Facebook account
  2. Navigate to settings
  3. Select the Apps option
  4. Locate the login data for your app
  5. Click on the "X" button to remove it

After following the steps above, attempt to log in to Facebook again.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Managing a variety of users within a Node.js Express application

Exploring the world of NodeJs, I am embarking on the journey of constructing a blogging API using node and express. Seeking guidance on implementing the following tasks : Users can view other user's profiles, but cannot make edits. Users can read any ...

Reverse changes made to a massive object and then redo them

My current project requires the implementation of undo-redo functionality for a product. At the moment, I am managing a substantial Object retrieved from a MongoDB collection The structure is as follows: { cart:{ products:[ { name: " ...

Y is not linked to X (ExpressJS / Sequelize)

I'm currently learning about NodeJS, express, and Sequelize. I encountered an issue when trying to create a book rental - the console displays "Book is not associated to Rent." After migrating the tables to the SQL database, everything seems to be in ...

I have been encountering an error consistently whenever I attempt to access the _id parameter in my angular front-end

EmployeeComponent.html: 11 ERROR TypeError: Cannot read property '_id' of undefined This is the error I encounter whenever I attempt to access the id in my front-end implementation using Angular. I have attempted incorporating ngIf, but unfo ...

Using Express.js to leverage Vega for generating backend plots

Exploring ways to create plots using backend code and transfer them to the front end for display. Could it be feasible to generate plots on the server-side and then transmit them to the front end? I am interested in implementing something similar to this: ...

My attempts to implement multi-container service deployment using NextJS and a backend node app have been unsuccessful

Currently, I am delving into the world of docker. Within my repertoire, I possess a mix of a next.js app and a node.js app. Within my next.js application, specifically in page.tsx, I have incorporated a call to my backend API. export const revalidate = 0; ...

SSL Error occurred: CERT_UNTRUSTED when executing npm command

I encountered an issue while attempting to install the express framework using the npm command. The error message is as follows: E:\myFindings\nodejs_programs\node>npm install -g express npm http GET https://registry.npmjs.org/express np ...

Utilizing express-handlebars to access variables that have been declared within the client-side javascript

Currently, I am delving into the world of handlebars for templating on my website. As a user of node.js, I opted to utilize the popular express-handlebars module due to its extensive support within the community. Setting up the basic configuration was str ...

Integrating SSL for Nuxt.js 3.9 in a Live Setting

I have a unique project in the works, where I am combining Vue.js/Nuxt.js frontend with Java Spring backend. To streamline deployment, I containerized both components into a single Docker image and then deployed it to a Kubernetes cluster on a different ne ...

Establishing the Session Once Headers are Established

Currently, I am working on implementing an asynchronous method that involves making a POST call to a specific API to fetch data and then storing the result in the user's session. Although the task itself seems straightforward, it becomes challenging w ...

Having issue updating a MySQL table using an array of objects in JavaScript

Working on a personal project involving React.js for the front-end, Node.js/express for the back-end, and mySQL for the database. The current array is as follows: horaires = [ { jour: 'Lundi', horaire: 'Fermé' }, { jour: 'Mar ...

What is the best method for serving static files within a nested EJS view directory?

Assuming I have the directory structure below: |--Views/ | --partial/ | --links.ejs | |--assets/ | --css/ | --styles.css | |--server.js Code for links.ejs <link rel="stylesheet" type="text/css" href="css/forms/switches.css"& ...

The backend post request is returning only "undefined" in JavaScript

Hey there, I'm still learning JS so please bear with me. I've been working on incrementing a value in a JSON file within my JS backend app. However, whenever I try to increase the associated value by the key, it ends up creating a new section la ...

Utilize Angular 9 with an M1 Mac device

Struggling to get my project, which utilizes Node 12 and Angular 9, up and running on my new M1 Mac. I used nvm to install node and the latest npm version, then ran the command npm i -g @angular/cli@9 to install angular. Even though which ng confirms that ...

A straightforward method to flatten and unflatten JSON files

I've managed to flatten JSON files effortlessly by executing this command in a combination of Node.js and Bash: npx flat foo.json > bar-flat-output.json. But now, I'm searching for another foolproof command that can easily undo the flattening ...

Is it possible to vite package projects with node.js back-end?

Is it possible to package a back-end project using Vite, such as Express or Koa? What is the process for packaging a Node.js back-end project? ...

React Native Child Component State Update Issue

In my code, there is a Child component that triggers a function in the Parent component. However, when the function is triggered, an error related to the setState method is thrown. Issue with Promise Rejection (id: 0): The '_this12.setState' i ...

What is the best way to distribute shared client-side javascript code among NodeJS projects?

As a newcomer to Node, I am embarking on a journey with a few web app projects using Express. Across these projects, there are some client-side libraries that I would like to share. It seems like a common issue with many possible solutions already in exist ...

Instruct npm to search for the package.json within a designated directory

Imagine having a folder structure that looks like this: root |-build |-package.json |-src |-foo |-foo.csproj |-foo.cs |-bar.cs |-bin |-... |-foo.sln Now, if you change the current directory to root\src\foo\bin a ...

Develop an extensive Typescript and React shared library

Trying to develop a shared React and Typescript library has been quite challenging. Configuring the project workspace to work on both the library and application simultaneously has proven to be more difficult than anticipated. project ├─ app │ ├ ...