0

我以为我正确地遵循了所有文档来实现这一点,但是,我收到了一个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 的代码时会出现错误。谁能给我指出一个方向,以便更好地解决这个问题?提前致谢。

4

1 回答 1

0

我找到了一个适合我的解决方案,但我仍然不清楚它是否是“最佳实践”。我希望有更多 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-09-11T09:46:54.753 回答