【问题标题】:GCP Consume a REST API after OAuth in Node.jsGCP 在 Node.js 中的 OAuth 之后使用 REST API
【发布时间】:2018-08-04 18:06:37
【问题描述】:

我正在努力实现一个要部署在 GCP App Engine 上的 Node.js Web 应用。

按照Node.js Bookshelf App 示例,我确实设法使用passport-google-oauth20 实现了一个基本的用户身份验证流程并检索了基本的个人资料信息。我基本上只是摆脱了我不需要的东西

我的自定义代码位于:gist.github.com/vdenotaris/3a6dcd713e4c3ee3a973aa00cf0a45b0

但是,我现在想使用 GCP Cloud Storage API 来检索具有记录身份的给定存储桶中的所有存储对象。 这应该可以通过:

  • 为请求添加适当的范围。
  • 使用通过 OAuth 获得的用户会话令牌对 REST 请求进行身份验证。

关于 post-auth 处理程序,文档说:

获取凭据后,您可以存储有关 用户。 Passport.js 自动将用户序列化到会话。 用户信息在会话中后,可以做一对 中间件功能,以更轻松地进行身份验证。

// Middleware that requires the user to be logged in. If the user is not logged
// in, it will redirect the user to authorize the application and then return
// them to the original URL they requested.
function authRequired (req, res, next) {
  if (!req.user) {
    req.session.oauth2return = req.originalUrl;
    return res.redirect('/auth/login');
  }
  next();
}

// Middleware that exposes the user's profile as well as login/logout URLs to
// any templates. These are available as `profile`, `login`, and `logout`.
function addTemplateVariables (req, res, next) {
  res.locals.profile = req.user;
  res.locals.login = `/auth/login?return=${encodeURIComponent(req.originalUrl)}`;
  res.locals.logout = `/auth/logout?return=${encodeURIComponent(req.originalUrl)}`;
  next();
}

但我看不到令牌的存储位置、如何检索它以及如何使用它来使用 Web 服务(在我的例子中是 GCP 存储)。

我根本不是 node.js 专家,所以最好能更清楚一点:有人可以解释我如何使用记录的用户凭据(因此 IAM/ACL 权限)继续使用 REST API )?

【问题讨论】:

    标签: node.js google-app-engine google-cloud-platform google-oauth passport.js


    【解决方案1】:

    如果您想通过使用通过 OAuth 获得的令牌访问 Cloud Storage,当应用程序需要用户数据时,它会提示同意屏幕,要求用户授权应用程序获取他们的部分数据。如果用户批准,则会生成访问令牌,可以将其附加到用户的请求中。这更好解释here

    如果您计划在Google App Engine 中运行您的应用程序,将会有一个包含必要身份验证信息的服务帐户,因此无需进一步设置。您可能需要生成 service account credentials(通常为 JSON 格式),必须将其添加到 gcloud 中的 GOOGLE_APPLICATION_CREDENTIALS 环境变量中。

    这是一个示例,说明如何使用在上一步中获得的令牌来验证和使用 REST API。例如,这将是一个列出存储在存储桶中的对象的请求:

    GET /storage/v1/b/example-bucket/o HTTP/1.1
    Host: www.googleapis.com
    Authorization: Bearer [YOUR_TOKEN]
    

    【讨论】:

      猜你喜欢
      • 2013-06-18
      • 2022-01-03
      • 1970-01-01
      • 2014-12-24
      • 2020-07-24
      • 2013-07-14
      • 2021-02-09
      • 2023-04-01
      • 2014-09-21
      相关资源
      最近更新 更多