调用回调URL时出现“令牌错误:错误请求”

时间:2020-04-07 16:29:54

标签: javascript express oauth-2.0 passport.js

每当我使用google-Oauth2调用回调URL时,都会得到以下提示。

错误回溯:

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);
                  });
            }
        })



    })
);

回调路由:

 //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');
    });

我是这个领域的新手。谁能告诉我为什么我会收到此错误?

1 个答案:

答案 0 :(得分:0)

u必须使用 passport.serializeUser 并在其中调用done方法, 在您正在其中使用 passport.authenticate 的路由上,也使用 passport.initialize方法作为中间件 遇到了同样的问题,这对我有用