Encountering a "Token Error: Bad Request" when attempting to call the callback URL

Every time I try to invoke the callback URL with google-OAuth2, I encounter the following error:

Error Traceback:

TokenError: Bad Request
    at Strategy.OAuth2Strategy.parseErrorResponse (G:\projects\oauth\node_modules\passport-oauth2\lib\strategy.js:358:12)
    at Strategy.OAuth2Strategy._createOAuthError (G:\projects\oauth\node_modules\passport-oauth2\lib\strategy.js:405:16)
    at G:\projects\oauth\node_modules\passport-oauth2\lib\strategy.js:175:45
    at G:\projects\oauth\node_modules\oauth\lib\oauth2.js:191:18
    at passBackControl (G:\projects\oauth\node_modules\oauth\lib\oauth2.js:132:9)
    at IncomingMessage.<anonymous> (G:\projects\oauth\node_modules\oauth\lib\oauth2.js:157:7)
    at IncomingMessage.emit (events.js:203:15)
    at endReadableNT (_stream_readable.js:1145:12)
    at process._tickCallback (internal/process/next_tick.js:63:19)

GoogleStrategy:

passport.use(
    new GoogleStrategy({
    //options for the gooogle strategy

        clientID: keys.google.clientID,
        clientSecret: keys.google.clientSecret,
        callbackURL:"http://localhost:3000/auth/google/redirect",

    },(accessToken,refreshToken,profile,done) => {
        // Check if user exist in our database
        User.findOne({googleId: profile.id}).then((currentUser)=>{
            if(currentUser){
                // already have the user
                console.log('user is ', currentUser);
                done(null,currrentUser);
            }else{
                // if not create a user in db
                new User({
                    username: profile.displayName,
                    googleId: profile.id 
                  }).save().then((newUser) =>{
                     console.log('new user created' , newUser);
                     done(null,newUser);
                  });
            }
        })



    })
);

Callback Routes:

 //auth with google 
    router.get('/google',passport.authenticate('google',{
        scope:['profile']
    }));

    //callback for google to redirect to
    router.get('/google/redirect',passport.authenticate('google'),(req,res) =>{
        //res.send(req.user);
        res.redirect('/profile');
    });

I am completely new to this field. Could someone explain why I am facing this error?

Answer №1

To resolve the issue, make sure to incorporate passport.serializeUser and invoke the done method within it. Additionally, apply passport.initialize method as middleware on the routes where you are utilizing passport.authenticate. I faced a similar challenge and this solution proved effective for me.

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

Arranging multiple Label and Input fields in HTML/CSS: How to create a clean and

I'm struggling with HTML and CSS, trying to figure out how to align multiple elements on a page. I've managed to line up all the rows on the page, but for some reason, the labels are appearing above the input fields when I want them to appear be ...

"Troubleshooting issue: Vue deep watch failing to detect changes in object properties

My initial data consists of a `customer` object. As I input text into various fields, different keys are added to the object. The watcher function triggers properly when a new key is added, but if an existing key is edited with a new value, the watcher doe ...

Express error handler failed to catch the validation error

I have a field type in my mongoose schema that is required. I've implemented a custom error handler in express like this: const notFound = (req, res, next) => { const error = new Error(`Not found-${req.originalUrl}`); res.status(404); next(er ...

A visually stunning image showcase with dynamic resizing and strategically placed white spaces using the m

I'm attempting to create a responsive image gallery using the Masonry jQuery plugin, but despite reading numerous articles and forum posts on the topic, I can't seem to get it to work properly. The gallery is displaying many blank spaces. My app ...

Setting up an object with a set expiration using NodeJS and Mongoose

Is there a way to create a temporary entity (like an ad) that will automatically expire after one month using NodeJS with MongoDB? An ideal comparison would be Instagram or Facebook Stories that only last for 24 hours. ...

I am interested in merging the outputs of two separate routers into a single router within Express.js

Having two different routers, each providing accurate results for separate views. However, the challenge is to combine both results into one view (Index). router.get('/', ensureAuthenticated, (req, res) => { if(req.query.search){ const r ...

Flask Server produces a response with a considerable delay when accessed through AJAX

I am currently running 2 servers on localhost, each with different ports. One of them is a basic flask server in Python and its code is provided below: from flask import Flask,jsonify from flask_cors import CORS app = Flask(__name__) CORS(app) @app.rout ...

"jQuery's .each() method is only iterating through the last element in

I am encountering an issue with this function not operating correctly... only the last Element shows the box. NOTES: <aside> is set to position: fixed; and I understand that this is not the "correct" use of <article> tags, but it helps me dist ...

How should I integrate my JS authentication function in Rshiny to enable the app to utilize the outcome?

Currently, I have an Rshiny application set to be published on the server but in order to ensure that a specific user has access, we require an API authentication token. The process of authentication is handled within JS tags outside of the application, wh ...

Puppeteer cannot fully render SVG charts

When using this code in Try Puppeteer: const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://www.barchart.com/futures/quotes/ESM19/interactive-chart/fullscreen'); const linkHandlers = await pa ...

Include characteristics in JSX.Element following its declaration

Suppose I have an item in a dictionary with the following structure: let item = { element: <myElement/>, color: "#0e76a8" } Is it possible to add a style attribute to the item.element within the render() method? I tried the following appro ...

I am looking to record my data by utilizing getInitialProps() in next.js

Being a beginner in next.js and react, I am eager to retrieve data from this particular free API link: The component index.js is as follows: import UserList from "./userList"; export default function Home() { return ( <div> &l ...

Guide to making a language selection wrapper using a gist script

Currently, I have a Gist file that is written in various languages but all serve the same purpose. As a result, I am interested in developing a language selection feature similar to what is found in the Google docs documentation. https://i.stack.imgur.com ...

Efficient methods for transferring information between a main and pop-up page within angularjs

On my webpage, I have a button that opens a popup page. I need to figure out a way to transfer json data from the main page to the popup page. These two pages are running separate angular applications. Once the data is transferred, it will be updated base ...

When trying to submit a form, encountering an `Uncaught ReferenceError` due to calling ajax within

Attempting to trigger an ajax function within a form in order to retrieve a value for the dropdown. mypython.py @app.route('/new_data', methods = ['POST', 'GET']) def new_data(): #Filter data and return the data(data_lis ...

What is the best method for adding files to JSZip from a remote URL?

Is it possible to load files into a Zip folder from a specified URL? For example: var zip = new JSZip(); zip.file("file.txt", "/site.net/files/file.txt"); Update I am following this example: I attempted the code provided but it was unsuccessful. I do ...

Problem with AngularJS factory causing issues with promises

I have a factory in AngularJS set up like this: 'use strict'; angular.module('frontRplApp') .factory('paymentService', function ($rootScope, $http, config, tools) { var urlBase = config.baseUrl; var payme ...

Leveraging Shared Functions Across Various Routes in Express with Node.js

Is there a way to implement shared methods/functions that can be utilized by various routes created in express within nodejs? I have developed a nodejs server which currently supports 3 APIs. For instance: /cars /cars/:id /cars/:id/sellers All these 3 A ...

Is your Cloud Functions task generating an Array when querying?

To access items and products in my database, I need to retrieve the "ean" field from the product and check if it matches the one in the request body. The structure of my database is as follows: "cart": { "items": { "0": {info here}, "1": {info ...

Why is it that GetElements does not provide immediate results upon execution?

Just diving into the world of Javascript for the first time and experimenting with it on Chrome, but running into unexpected results. When I try: document.getElementsByTagName("h1") I anticipate seeing: <h1>tester h1 in body</h1> Instead, wh ...