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

Tips for preventing text from changing its padding within a div when reducing the width and height dimensions

I am facing an issue with a div inside another div. The child div contains text, and when I apply animation to decrease the width and height, the text inside gets reset according to the new size. While I understand why this happens, I want to find a way to ...

Tips for storing mustache templates for rendering in Node.js

My data is stored in the following format: let data = {"list" :[ { "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="98f9fafb8afef0f9f5e8f4fdb6fbf7f5">[email protected] ...

Developing in Java Script with ENVDTE involves adding a new project to an existing solution and placing it in a designated sub-folder for organization purposes

Currently, I am working on developing a Visual Studio extension for a new C++ project template using Visual Studio 2010. The approach I am taking involves utilizing the .vsz template method and customizing the default.js code to suit my requirements. Withi ...

Angular Promises - Going from the triumph to the disappointment callback?

It seems like I might be pushing the boundaries of what Promises were intended for, but nonetheless, here is what I am attempting to do: $http.get('/api/endpoint/PlanA.json').then( function success( response ) { if ( response.data.is ...

Unable to assign a value to the property of the socket.io handshake object

I am attempting to include a custom attribute in a socket.io handshake and transfer it to the socket object upon each connection. Below is a basic outline of my approach: var app = express(); var http = require("http").Server(app); var io = require("soc ...

The button click event fails to trigger after entering text into an input field

I created a basic calculator. Users can input a value in the designated field and then click on the '+' button. The cursor stays in the input field, allowing users to immediately enter a new value after clicking the '+'. The mouse poi ...

The Angular application must remain logged in until it is closed in the browser

Currently, my Angular app includes authentication functionality that is working smoothly. The only issue is that the application/session/token expires when there is no user activity and the app remains open in the browser. I am looking for a solution wher ...

Error encountered: Unable to render template at an unidentified path in a NODE JS environment

I am currently working on a HTML page with the help of node js. This is the code I have written for running app.js: app.get('/',function(req,res)){ res.render('index',{"data":["name" , "ABC"] }); }); In order to display the na ...

Using AJAX to pass the ID name when clicking in PHP

Currently, I am in the process of implementing an Ajax-driven filtered search system that consists of three distinct tabs. These tabs allow users to search by names, category, and location. I have successfully enabled searching when a user types a name int ...

Is it detrimental to my search engine ranking if I utilize CSS display:none?

Imagine having valuable content that is initially hidden with CSS, and then using javascript to reveal it only when the user clicks on certain links. Even users without javascript enabled can access this content by following the links to a new page where i ...

discovering the category for the .click function

After retrieving a list of book objects from a JSON object, I am in the process of displaying them on an HTML page by creating buttons with titles. The goal is to alert the URL of the book when a button is clicked. However, I am facing an issue with access ...

Setting the cache to false during an httpget request in an mvc4 controller action: tips and tricks

My httpget request to a controller action looks like this: $.get('/Course/ExplanationCorrect/', postData, function (data) { $('#SurveyDiv').html(data); }); While it works on all other browsers, I'm facing an issue with IE10 o ...

"Webpack-dev-server is having trouble locating the React index file. Let's troubleshoot this issue and

I am new to Express and server-side development in general. For my small React messaging app, I am using Express for the backend (a JSON file) and webpack dev server for the frontend. When I start just the webpack server, the app displays correctly. Proble ...

Error code 404 was received from the API request made by the Flutter application, indicating that

The GET all and POST methods via API are functioning properly, but the UPDATE API is returning a status code of 404. https://i.sstatic.net/UUnud.png https://i.sstatic.net/Al7X3.png // In the NodeJs update method below, we attempt to update a product using ...

In order to properly set up Require JS, you will need to configure the JS settings

Is there a way to specify the path from any property inside the require JS config section? We are trying to pass a property inside the config like so: The issue at hand: var SomePathFromPropertyFile = "CDN lib path"; require.config({ waitSeconds: 500 ...

Tips for importing resources in Webpack and Express.js without relying on a front-end framework

Currently, I'm developing a basic Express.js application without incorporating any client-side frameworks such as React, Vue, or Angular. The HTML templates are rendered from the server in the following manner: app.get('/', function (req, r ...

Issue with FullPageJS: scrollOverflow feature not functioning upon click event

I am currently working on a Fullpage.js instance that needs to be initialized with a click event and then destroyed when switching to another page, and vice versa. The scrollOverflow feature works perfectly as long as the #fullpage element is not hidden up ...

Looking for solutions to manage mouseenter, mouseleave events and ensuring content dropdowns stay visible in Vue.js 2?

Hey there, I'm trying to figure out how to keep dropdown content from disappearing when using @mouseenter and @mouseleave. Here's what I have so far: <div class="wrapper"> <div class="link" @mouseenter="show = ...

Encountered an issue with a module not being found while trying to install a published React component library that is built using Rollup. The error message states:

In my latest project, I have developed a React component library called '@b/b-core' and used Rollup for building and publishing to the repository. When trying to install the library in a React app, an issue arises where it shows Module not found: ...

Switching effortlessly between Fixed and Relative positioning

As I work on creating a unique scrolling experience, I aim to have elements stop at specific points and animate before returning to normal scroll behavior once the user reaches the final point of the page. Essentially, when div X reaches the middle of the ...