【问题标题】:Getting "Token Error: Bad Request" while invoking callback URL调用回调 URL 时获取“令牌错误:错误请求”
【发布时间】:2020-07-19 22:16:40
【问题描述】:

每当我使用 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)

谷歌策略:

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

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

【问题讨论】:

    标签: javascript express oauth-2.0 passport.js


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-04
      • 2019-06-23
      • 2016-06-22
      • 1970-01-01
      • 1970-01-01
      • 2021-10-31
      • 2011-10-25
      相关资源
      最近更新 更多