【问题标题】:Trying to use Google Oauth2 with Passportjs in Graphql-Yoga Server尝试在 Graphql-Yoga 服务器中使用 Google Oauth2 和 Passportjs
【发布时间】:2020-01-10 12:04:28
【问题描述】:

我认为我正确地遵循了所有文档来实现这一点,但是,我收到了一个 TokenError: Bad Request,其中包含错误消息 invalid_grant。

我的服务器超级简单:

require('dotenv').config();
import createServer from './createServer';

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

const server = createServer();

passport.use(
  new GoogleStrategy(
    {
      clientID: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
      callbackURL: 'http://localhost:4000/auth/callback',
    },
    (accessToken, refreshToken, profile, cb) => {
      console.log(accessToken);
      console.log(refreshToken);
      console.log(profile);

      cb(null, profile);
    },
  ),
);

server.express.use(
  '/auth',
  passport.authenticate('google', {
    scope: ['email', 'profile'],
    session: false,
  }),
);

server.express.use(
  '/auth/callback',
  passport.authenticate('google', {
    successRedirect: 'http://localhost:3000/authenticate',
    failureRedirect: 'http://localhost:3000/authenticate',
  }),
);

server.start(
  {
    cors: {
      credentials: true,
      origin: 'http://localhost:3000',
    },
  },
  () => console.log('Server is running on http://localhost:4000'),
);

这是我在云平台中设置 Google 的方式有问题吗?我不知道我哪里出错了。我的回调设置正确。我不知道还有什么地方可以查找错误?

另一件令人困惑的事情是,GoogleStategy 是控制台记录用户配置文件和返回的访问令牌。我猜当回调路由尝试验证来自 URL 的代码时会出现错误。任何人都可以为我指出一个更好地解决此问题的方向吗?提前致谢。

【问题讨论】:

    标签: node.js authentication passport.js graphql-js passport-google-oauth


    【解决方案1】:

    我找到了一个适合我的解决方案,但我仍然不清楚它是否是“最佳实践”。我希望有更多 GraphQL 经验的人加入。

    我按照文档中的说明在前端进行身份验证:https://developers.google.com/identity/sign-in/web/backend-auth

    然后我在后端编写了一个名为 isAuthenticated 的查询,我可以使用它来验证令牌。

    async isAuthenticated(_: any, { token }) {
        if(!token) {
          return null;
        }
    
        const ticket = await client.verifyIdToken({
          idToken: token,
          audience: process.env.GOOGLE_CLIENT_ID,
        });
    
        return payload;
      },
    

    在渲染任何受保护的路由之前,我使用 React 组件检查 localStorage 中的令牌。这对我有用。

    【讨论】:

    • 如果用户在访问您的私有路由之前手动更改本地存储怎么办?
    猜你喜欢
    • 2019-11-25
    • 2017-03-21
    • 2019-05-30
    • 2021-05-29
    • 2016-04-28
    • 2018-10-18
    • 2019-08-03
    • 2019-09-27
    • 2020-02-08
    相关资源
    最近更新 更多