首页 文章

使用Express和Passport的Google令牌身份验证无效

提问于
浏览
1

我用Express制作了一个REST api,它使用Passport和 passport-google-token 策略来验证用户身份 . 当我的服务器在localhost上运行时,它可以按预期工作,但它不能在服务器的实时版本上运行 . 所有呼叫都返回401 Unauthorized响应 .

护照策略配置如下:

this.passport.use(new GoogleTokenStrategy({
  clientID: this.config.auth.googleAuth.clientId,
  clientSecret: this.config.auth.googleAuth.clientSecret
}, (accessToken, refreshToken, profile, done) => {
  User.findOne({'google.id': profile.id}, (err, user) => {
    if(err) return done(err);
    if(user) return done(null, user);

    var newUser = new User();

    newUser.save((err) => {
      if (err) throw err;
      return done(null, newUser);
    });
  })
}));

这是一个 endpoints 的例子 . 当我使用有效的Google访问令牌命中它时,它会返回401响应,但仅在实时域上 - 它适用于localhost .

app.get("/api/exists", passport.authenticate("google-token"), (req, res) => {
  // stuff happens here
});

以下是我在Google API管理器中使用的凭据:
Google API credentials

如果相关,则在这种情况下,客户端是Chrome扩展程序,使用getAuthToken获取令牌 . 从客户端执行请求的代码如下所示:

chrome.identity.getAuthToken({"interactive": true}, (token) => {
  const bodyJson = body ? JSON.stringify(body) : null;
  const headers = new Headers();
  headers.append("Access_token", token);
  headers.append('Accept', 'application/json');
  headers.append('Content-Type', 'application/json');

  const request = new Request(url, {
    headers: headers,
    method: method,
    body: bodyJson
  });

  fetch(request);
});

但即使我从the Google oauth playground生成一个令牌并通过Postman发出请求,我也会得到相同的结果:它适用于localhost并且不适用于真实域 .

我还需要做什么来验证我的实时域中的用户?

1 回答

  • 1

    问题原来是我的Nginx服务器 . 默认情况下,它会删除包含下划线的 Headers (例如 access_token ) . 我没有想到问题就在那里,因此在我的问题中甚至没有提到它 .

    Docs about that are here . 您可以通过设置更改行为:

    underscores_in_headers on
    

相关问题