【问题标题】:InternalOAuthError: Failed to fetch user profileInternalOAuthError:无法获取用户配置文件
【发布时间】:2022-07-12 05:30:51
【问题描述】:

我正在尝试使用 passport.js 将 google auth 实现到 GraphQL API。流程似乎运行良好,我得到了一个带有正确用户信息编码的 jwt 令牌。但是,有时我的控制台中仍然会出现以下错误。任何帮助将不胜感激!

InternalOAuthError: Failed to fetch user profile
    at /Users/Lawand/Developer/mono-api/node_modules/passport-google-oauth20/lib/strategy.js:99:19
    at ClientRequest.<anonymous> (/Users/Lawand/Developer/mono-api/node_modules/oauth/lib/oauth2.js:162:5)
    at ClientRequest.emit (node:events:394:28)
    at ClientRequest.emit (node:domain:475:12)
    at TLSSocket.socketErrorListener (node:_http_client:447:9)
    at TLSSocket.emit (node:events:394:28)
    at TLSSocket.emit (node:domain:475:12)
    at emitErrorNT (node:internal/streams/destroy:157:8)
    at emitErrorCloseNT (node:internal/streams/destroy:122:3)
    at processTicksAndRejections (node:internal/process/task_queues:83:21)

我的护照配置文件:

passport.use(
    new GoogleStrategy(
      {
        clientID: process.env.GOOGLE_CLIENT_ID as string,
        clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
        callbackURL: 'http://localhost:4001/auth/google/callback',
        passReqToCallback: true,
      },
      (req, _accessToken, _refreshToken, profile, done) => {
        try {
          User.find({
            where: { id: profile.id },
          }).then((res) => {
            console.log(res)
            if (res.length === 0) {
              const newUser = {
                id: profile.id,
                firstName: profile.name?.givenName,
                lastName: profile.name?.familyName,
                email:
                  profile.emails &&
                  profile.emails[0] &&
                  profile.emails[0].value,
              }
              User.create({
                input: [newUser],
              }).then(() => {
                req.user = profile
                done(null, profile)
              })
            }
          })
          req.user = profile
          done(null, req.user)
        } catch (error: any) {
          done(error)
        }
      }
    )
  )

然后将请求传递给回调:


const startApolloServer = async () => {
  const app = express()
  const httpServer = http.createServer(app)
  /*
   * Create an executable GraphQL schema object from GraphQL type definitions
   * including autogenerated queries and mutations.
   * Read more in the docs:
   * https://neo4j.com/docs/graphql-manual/current/
   */
  const neoSchema = new Neo4jGraphQL({
    typeDefs,
    driver,
    config: {
      jwt: {
        secret: process.env.JWT_SECRET as string,
      },
    },
  })

  // Same ApolloServer initialization as before, plus the drain plugin.
  const server = new ApolloServer({
    context: ({ req }) => ({ req }),
    schema: neoSchema.schema,
    plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],
  })

  googlePassportConfig()

  app.use(passport.initialize())

  app.get(
    '/auth/google',
    passport.authenticate('google', {
      scope: ['profile', 'email'],
    })
  )
  app.get(
    '/auth/google/callback',
    passport.authenticate('google', {
      failureRedirect: 'http://localhost:4001/graphql',
      session: false,
      scope: ['profile', 'email'],
      passReqToCallback: true,
    }),
    (req: any, res) => {
      const token = jwt.sign(
        { id: req?.user?.id },
        process.env.JWT_SECRET as string,
        { expiresIn: '7d' }
      )
      res.json({ token })
    }
  )

  // More required logic for integrating with Express
  await server.start()
  /*
   * Optionally, apply Express middleware for authentication, etc
   * This also also allows us to specify a path for the GraphQL endpoint
   */
  server.applyMiddleware({
    app,
    path,
  })

  // Modified server startup
  httpServer.listen({ host, port, path }, () => {
    console.log(`???? GraphQL server ready at http://${host}:${port}${path}`)
  })
}

startApolloServer()

【问题讨论】:

  • 我也有同样的问题~~~ 'passport-google-oauth20' 和 'passport-google-oauth2' 都有同样的问题

标签: passport.js apollo-server passport-google-oauth


【解决方案1】:

我遇到了同样的错误,最终解决了我的问题是从我的路由 index.js 中的 bodyParser 更改为中间件的 app.use(express.json())。这完全解决了我的错误,此后一直运行良好。

【讨论】:

    猜你喜欢
    • 2016-06-04
    • 2022-08-16
    • 1970-01-01
    • 2022-11-11
    • 2019-03-25
    • 2014-05-25
    • 1970-01-01
    • 2020-04-14
    • 2019-04-07
    相关资源
    最近更新 更多