The passport has an expired or incorrect code entered

I'm encountering an issue where the code passed is showing as incorrect or expired.

The specific error message reads: "TokenError: The code passed is incorrect or expired."

GET /api/users/auth/github/callback?code=afefcf8b12561c910798 - - ms - - [0] undefined [0] TokenError: The code passed is incorrect or expired. [0] at Strategy.OAuth2Strategy.parseErrorResponse (/Users/eli/nodework/sequelize-demo/node_modules/passport-oauth2/lib/strategy.js:329:12) [0] at Strategy.OAuth2Strategy._createOAuthError (/Users/eli/nodework/sequelize-demo/node_modules/passport-oauth2/lib/strategy.js:376:16)

Despite setting up passport-github auth properly, even after resetting all tokens, the error persists.

config/passport-config.js

const GitHubStrategy = require('passport-github').Strategy;
const models = require( '../models/index');
require('dotenv').config();


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

  // from the user id, figure out who the user is...
  passport.deserializeUser(function(userId, done){
    models.User
      .find({ where: { id: userId } })
      .then(function(user){
        done(null, user);
      }).catch(function(err){
        done(err, null);
      });
  });


  passport.use(new GitHubStrategy({
      clientID: process.env.clientID,
      clientSecret: process.env.secret,
      // if the callback is set to 5000 the 0auth app will not work for some reason
      callbackURL: 'http://127.0.0.1:5000/api/users/auth/github/callback'

    },
    function(accessToken, refreshToken, profile, cb) {
      models.User.findOne({ where: {'id': profile.id } }, 

      function (err, user) {
        if(err) {
          console.log(err);  // handle errors!
        }
        if (!err && user !== null) {
          done(null, user);
        } else {
          models.User.create({
            id: profile.id,
            username: profile.displayName,
            createdAt: Date.now()

          }).then(user => {
            console.log( refreshToken );
            console.log('user created');
            return done(null, user);
          });

        }
      });
    }
  ));
};

routes/users.js

router.get('/auth/github', passport.authenticate('github') );

router.get('/auth/github/callback', 
  passport.authenticate('github', { failureRedirect: '/' }),
  function(req, res) {
    // Successful authentication, redirect home.
    res.redirect('/dashboard');

    console.log('this works');
});

Answer №1

Credited by this repository

Link to the server.js file

config/passport-github.js

  passport.use(new GitHubStrategy({
      clientID: process.env.clientID,
      clientSecret: process.env.secret,
      // changing the callback URL seems to resolve authentication issues
      callbackURL: 'http://127.0.0.1:5000/api/users/auth/github/callback'

    },
    function(accessToken, refreshToken, profile, cb) {

      models.User
      .findOrCreate({where: {id: profile.id}, defaults: {username: profile.displayName}})
      .spread(function(user, created) {
        cb(null, user)
      });

router.get('/auth/github', passport.authenticate('github', { session: false, scope: ['profile'] }) );

router.get('/auth/github/callback', 
  passport.authenticate('github', { failureRedirect: '/' }),
  function(req, res) {
    // Redirecting to dashboard upon successful authentication
    res.redirect('http://127.0.0.1:3000/dashboard');

    console.log('this works');
});

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

Building a dynamic webpage using AJAX, MVC, and web APIs to generate a div element filled

I'm currently working with a restful API, MVC, and ajax. My goal is to retrieve data from the backend and then display images within certain div elements. The expected outcome should resemble this example: https://i.stack.imgur.com/BFqWL.png This sni ...

Using *ngIf and *ngFor in Angular to switch between divs depending on their index values

Is there a way to toggle between two divs based on the index value using *ngIf in Angular? I have attempted to do so by toggling boolean values of true and false, but my current approach is not working. Here is what I have tried so far: <div *ngFor=&qu ...

Tips for utilizing Ajax POST with jQuery in JSP?

Everything seems to be working smoothly up until I encounter an issue: $('#loginForm').attr('method', 'POST'); $('#loginForm').attr('action', basePath + url); After this, I decide to create a callback fun ...

Is there a way to trigger the bootstrap datetimepicker when a custom button is clicked, while also storing the selected value in a hidden textbox

When the ADD button is clicked, a datetimepicker should open. After selecting a value from the datetimepicker, it should be saved in the textbox with ID #myTextBox. <div> <input id="myTextBox" type="text" ng-model="c" data-provide="datepicker ...

Angularjs: The Art of Loading Modules

I am facing an issue while trying to load certain modules. controller1.js: angular.module('LPC') .controller('lista_peliculas_controller', ['$scope', function($scope) { $scope.hola="hola peliculas"; }]); And ap ...

There appears to be an issue with the functionality of the external CSS pathway

placeholder image hereplaceholder image hereplaceholder image here I'm encountering a problem and struggling to identify the mistake in my current approach. ...

Is there a way to remove a certain child category post from appearing in a parent category?

I'm having trouble with displaying related posts by category while excluding a specific category. I've tried different methods but none seem to work, and I'm not sure how else to approach this issue. <?php $categories = get_the_terms ...

Why is it that the document.execCommand("copy") function is not functioning within the content script of my chrome extension?

I am trying to implement a feature in my Chrome extension where I can write data to the clipboard. I have already specified permissions for clipboardRead and clipboardWrite in the manifest file. I came across a function that I thought would work, which I ...

What is the best location in Backbone.js to store code unrelated to the view, such as ads and analytics?

In my development of a backbone.js application, I have come to understand the role of each backbone "class" as follows: Model: This represents the data object, where the outcome of an API call is stored. Collection: An organized group of models, for exam ...

The tooltip feature is malfunctioning

The content: <table class="table table-hover"> <?php foreach ($query as $row){ echo '<tr ><td > <label class="checkbox"> '.form_checkbox('delete[]', $row['link']).anchor("site ...

Tips on using the .map() method to extract data from a JSON response received from a get request and utilizing the content within a specific index to populate table rows

Here is the JSON response representation, https://i.stack.imgur.com/0QWkv.png This is how my project displays it: https://i.stack.imgur.com/LnA5v.png The rendering code snippet is as follows: render() { const { materials } = this.state; ...

Is there a way to prevent a page from rendering until the necessary data is retrieved?

I am facing an issue where my page is attempting to render before the data is available. I have used async/await in my code, but I keep getting an error saying that the data is undefined. Interestingly, when I comment out the page elements and check the Re ...

On hover, HTML5 animations smoothly transition a dashed border inward

I'm in the process of creating a drag and drop module and I want to ensure that as the user drags an item, the dashed line around the outside moves inward and the box changes color. However, I don't want the appearance of the dashed line to chang ...

An automated solution designed to launch external website links in a new tab or window

I currently have a website where links open in the same window if they lead to pages on my site, and in a new window if the domain is different. However, I'm using manual code like this: <a href="http://www.example.com" target="<%=checkdomain(" ...

Having trouble establishing a connection between Node.js and SQL Server using Tedious library

When attempting to connect to a local SQL Server instance using Node.js and Tedioius, I encounter the following error: { [ConnectionError: Failed to connect to XXXXX:1433 - connect ECONNREFUSED] name: 'ConnectionError', message: 'Failed ...

Can jQuery Autocomplete function without stopping at white spaces?

Is there a way to modify jQuery UI autocomplete so that it can handle multiple words instead of terminating with a space? For example, if you input "New York City", it should still filter results based on each word. $.ajax({ type: "GET" ...

Transferring a boolean model value to a JavaScript function triggers a reference to the onchange function

An onchange event is triggered in an input tag of type checkbox, calling a JavaScript function and passing three parameters from the model: <input type="checkbox" ... onchange="changeRow('@Model.Id', '@Model.Type', @Model.AwaitingAp ...

Ionic app encounters issue fetching local JSON data

I have been working on my Ionic application and I encountered an issue when trying to load local JSON data into it. I set up a http.get in my javascript to retrieve the data, but for some reason it's not showing up in the application. It seems like th ...

Retrieving attribute of a span element inside a nested div

Newbie to web scraping and facing an issue. I am trying to extract the value of data-value from the span with class "DFlfde SwHCTb". However, I keep getting an undefined return. Can someone point out what error I made in the code below? const axios = requi ...

What is the best way to send a Date to a node.js or express.js server?

Currently, I am utilizing node.js with express as the backend for my project. I have multiple objects that contain date-type properties. However, whenever I post them to my webservices, the date gets converted to a string. Is there a way or format in whic ...