Strategy.OAuth2Strategy.parseErrorResponse发生错误-NodeJS护照Google oauth2.0

时间:2018-07-07 18:55:04

标签: node.js express passport.js google-oauth google-login

我正在尝试使用通行证和Google Passport-google-oauth20将Google身份验证嵌入到Node.js中。问题是当Google回调路由打开时,我得到:

Error
at Strategy.OAuth2Strategy.parseErrorResponse (E:\Programowanie\NodeJS\Hydronide\node_modules\passport-oauth2\lib\strategy.js:329:12)
at Strategy.OAuth2Strategy._createOAuthError (E:\Programowanie\NodeJS\Hydronide\node_modules\passport-oauth2\lib\strategy.js:376:16)
at E:\Programowanie\NodeJS\Hydronide\node_modules\passport-oauth2\lib\strategy.js:166:45
at E:\Programowanie\NodeJS\Hydronide\node_modules\oauth\lib\oauth2.js:191:18
at passBackControl (E:\Programowanie\NodeJS\Hydronide\node_modules\oauth\lib\oauth2.js:132:9)
at IncomingMessage.<anonymous> (E:\Programowanie\NodeJS\Hydronide\node_modules\oauth\lib\oauth2.js:157:7)
at emitNone (events.js:110:20)
at IncomingMessage.emit (events.js:207:7)
at endReadableNT (_stream_readable.js:1059:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)

我(或多或少)跟随this tutorial。 这是我的代码: 路由(以“ / auth”开头)

'use strict'

const passport = require('passport')
const router = require('express').Router()

router.get(
  '/google',
  (req, res, next) => {
    if (req.query.return) {
      req.session.oauth2return = req.query.return
    }
    next()
  },
  passport.authenticate('google', { scope: ['email', 'profile'] })
)

router.get(
  '/google/callback',
  passport.authenticate('google'),
  (req, res) => {
    const redirect = req.session.oauth2return || '/';
    delete req.session.oauth2return;
    res.redirect(redirect);
  }
);

module.exports = router

有一个护照配置:

'use strict'
const passport = require('passport')
const keys = require('./keys')
const GoogleStrategy = require('passport-google-oauth20').Strategy
const userController = require('../controllers/user-controller')

const passportConfig = {
  clientID: keys.google.clientId,
  clientSecret: keys.google.clientSecret,
  callbackURL: 'auth/google/callback',
  accessType: 'offline'
}

passport.use(new GoogleStrategy(passportConfig,
  (accessToken, refreshToken, profile, done) => {
  console.log(accessToken, refreshToken, profile, done)
  userController.getUserByExternalId('google', profile.id)
  .then(user => {
    if (!user) {
      userController.createUser(profile, 'google')
      .then(user => {
        return done(null, user)
      })
      .catch(err => {
        return done(err)
      })
    }
    return done(null, user)
  })
  .catch(err => {
    return done(err)
  })
}))

passport.serializeUser((user, cb) => {
  cb(null, user)
})
passport.deserializeUser((obj, cb) => {
  cb(null, obj)
})

如您所见,我已经在新的GoogleStrategy第二参数函数中添加了console.log,但是它从未触发。

//编辑 我注意到,我使用require('passport-google-oauth20').Strategy而不是分配require('passport-google-oauth20')。但是修复它并不会改变任何东西,仍然是相同的错误。 我可以添加的一个问题是,在我的主要失败中,我打电话给

// sets passport config
require('./config/jwt-auth')
require('./config/google-auth')

// initialize passport
app.use(passport.initialize())

所以我不希望那里有什么问题。

6 个答案:

答案 0 :(得分:2)

您可以通过在控制台模块的Oauth和Strategy中放置一些console.log来获得帮助,尤其是在日志中出现错误的那一行。

E:\Programowanie\NodeJS\Hydronide\node_modules\passport-oauth2\lib\strategy.js
E:\Programowanie\NodeJS\Hydronide\node_modules\oauth\lib\oauth2.js

这将帮助您了解解析错误的根本原因。似乎请求/响应数据存在一些问题。

答案 1 :(得分:1)

您必须在策略的callbackURL部分中指定完整的URL: 例如:如果在localhost:3000上使用以下代码在本地运行代码:

passport.use(new googleStrategy({
    clientID:keys.clientID,
    clientSecret:keys.clientSecret,
    callbackURL:'auth/google/callback'
},(accessToken,refreshToken, profile,done)=>{
    console.log(accessToken);
    console.log(refreshToken);
    console.log(profile);
}
));

app.get('/auth',passport.authenticate('google',{

    scope:['profile','email']
}));
app.get('/auth/google/callback', 
  passport.authenticate('google'));

上面的代码肯定会引发TokenError:错误的请求。您必须通过完整的URl才能获得最终代码,如下所示:

passport.use(new googleStrategy({
    clientID:keys.clientID,
    clientSecret:keys.clientSecret,
    callbackURL:'http://localhost:3000/auth/google/callback'
},(accessToken,refreshToken, profile,done)=>{
    console.log(accessToken);
    console.log(refreshToken);
    console.log(profile);
}
));

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

app.get('/auth/google/callback', 
  passport.authenticate('google'));

答案 2 :(得分:0)

我通过检查此路线解决了问题

AWSTemplateFormatVersion: 2010-09-09

Resources:
  MYLOGGROUP:
    Type: 'AWS::Logs::LogGroup'
    Properties:
      LogGroupName: index_slow

  MYESROLE:
    Type: 'AWS::IAM::Role'
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service: es.amazonaws.com
            Action: 'sts:AssumeRole'
      ManagedPolicyArns:
        - 'arn:aws:iam::aws:policy/AmazonESFullAccess'
        - 'arn:aws:iam::aws:policy/CloudWatchFullAccess'
      RoleName: !Join
        - '-'
        - - es
          - !Ref 'AWS::Region'

  PolicyDocESIndexSlow :
    Type: AWS::IAM::Policy
    Properties:
      PolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Action: 
             - logs:PutLogEvents
             - logs:CreateLogStream
            Resource: 'arn:aws:logs:*'
      PolicyName: !Ref MYLOGGROUP
      Roles:
        - !Ref MYESROLE

  MYESDOMAIN:
    Type: AWS::Elasticsearch::Domain
    Properties:
      DomainName: 'es-domain'
      ElasticsearchVersion: '7.4'
      ElasticsearchClusterConfig:
        DedicatedMasterCount: 3
        DedicatedMasterEnabled: True
        DedicatedMasterType: 'r5.large.elasticsearch'
        InstanceCount: '2'
        InstanceType: 'r5.large.elasticsearch'
      EBSOptions:
        EBSEnabled: True
        VolumeSize: 10
        VolumeType: 'gp2'
      AccessPolicies:
        Version: 2012-10-17
        Statement:
          - Effect: Deny
            Principal:
              AWS: '*'
            Action: 'es:*'
            Resource: '*'
      AdvancedOptions:
        rest.action.multi.allow_explicit_index: True
      LogPublishingOptions:
        INDEX_SLOW_LOGS:
          CloudWatchLogsLogGroupArn: !GetAtt
            - MYLOGGROUP
            - Arn
          Enabled: True
      VPCOptions:
        SubnetIds:
          - !Ref MYSUBNET
        SecurityGroupIds:
          - !Ref MYSECURITYGROUP
  MYVPC:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.0.0.0/16
  MYSUBNET:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref MYVPC
      CidrBlock: 10.0.0.0/16
  MYSECURITYGROUP:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: security group for elastic search domain
      VpcId: !Ref MYVPC
      GroupName: 'SG for ES'
      SecurityGroupIngress:
        - FromPort: '443'
          IpProtocol: tcp
          ToPort: '443'
          CidrIp: 0.0.0.0/0

我正在尝试对新用户进行操作,为此,我尝试从数据库中获取用户,如果可以的话,我会做这项工作,否则直接重定向到某个地方,但是我遇到的问题是 您可以通过安慰日志来检查此路线

答案 3 :(得分:0)

const express = require('express');
const router = express.Router();
const { User } = require('../models/user.model');
const jwt = require('jsonwebtoken');
const config = require('../config/config.json');
const role = require('../lib/role');


const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;

router.use(passport.initialize());

passport.serializeUser((user, cb) => {
  cb(null, user);
});


passport.deserializeUser((obj, cb) => {
  cb(null, obj);
});


passport.use(new GoogleStrategy({
  clientID: "sssssssssssssssssssssssssss",
  clientSecret: "Vsssssssssssssss",
  callbackURL: "http://localhost:4000/api/auth/google/callback"
},

  (request, accessToken, refreshToken, profile, cb) => {

    User.findOne({ email: profile.emails[0].value }, (err, user) => {
      if (err) {
        cb(err); // handle errors!
      }
      if (!err && user !== null) {
        cb(err, user);
      }
      else {

        user = new User({
          googleId: profile.id,
          email: profile.emails[0].value,
          firstname: profile.name.givenName,
          lastname: profile.name.familyName,
          role: role.Client,
          isActive: true,
          isGain: false,
        });

        user.save((err) => {
          if (err) {
            cb(err); // handle errors!
          } else {
            cb(null, user);
          }
        });
      }
    });
  }
));



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

// callback
router.get('/callback', passport.authenticate('google', { failureRedirect: '/failed' }),
  (req, res) => {
    const token = jwt.sign({ userId: req.user._id, email: req.user.email, role: req.user.role }, config.secret_key, { expiresIn: '10 h' })
    res.status(200).json({ success: true, token, expireIn: `${new Date().getTime() + 120000}` })
  }
);


//failed auth google 
router.get('/failed', async (req, res) => { res.status(404).send('erreur authentification') })





module.exports = router; 

答案 4 :(得分:0)

在passport.js中,您需要将callbackURL从'auth / google / callback'更改为'/ auth / google / callback'。不要忘记在身份验证之前添加“ /”。

passport.use(new googleStrategy({
    clientID:keys.clientID,
    clientSecret:keys.clientSecret,
    callbackURL:'/auth/google/callback'
},(accessToken,refreshToken, profile,done)=>{
    console.log(accessToken);
    console.log(refreshToken);
    console.log(profile);
}
));

答案 5 :(得分:0)

passport.use(new GoogleStrategy({
        clientID: process.env.CLIENT_ID,
        clientSecret: process.env.CLIENT_SECRET,
        callbackURL: "http://localhost:3000/auth/google/home"
    },
    function(accessToken, refreshToken, profile, cb) {
        console.log(profile);
        User.findOrCreate({ username: profile.displayName, googleId: profile.id }, 
    function (err, user) {
        return cb(err, user);
    });
}));