Google OAuth2 的 RSA 私钥/公钥

Pab*_*oya 2 node.js oauth-2.0 google-cloud-platform google-cloud-iam google-workspace

我正在使用 Google Cloud Platform 的服务帐户进行服务器到服务器的身份验证。根据Google 的文档,请求令牌 (JWT) 必须基于 RSA SHA-256 算法,因此使用 RSA 认证的私钥进行签名,并使用其各自的公钥进行解码。

我如何让 google api 知道公钥?

我知道 Google 有自己的RSA 证书,但我不知道如何准确使用它们。

那么,我应该使用什么 RSA 私钥/公钥来进行 google 的 oauth2 令牌编码?

这是代码的摘录:

import jwt from 'jsonwebtoken'
const axios = require('axios')
const fs = require('fs')
const {
  google
} = require('googleapis')

// oauth2 token uri
const GSUITE_AUD = 'https://oauth2.googleapis.com/token'

const payload = {
  iss: 'example@example.iam.gserviceaccount.com',
  scope: 'https://www.googleapis.com/auth/admin.directory.user',
  aud: GSUITE_AUD,
}

const options = {
  algorithm: 'RS256',
  expiresIn: '10m'
}

const fetchGSuiteUsersUtil = () => {
  let path = require('path'),
    privateKeyFilePath = path.join(__dirname, 'private.key')

  const privateKey = fs.readFileSync(privateKeyFilePath, 'utf-8')

  const request_token = jwt.sign(payload, privateKey, options)

  authorize(request_token, listUsers)

  function authorize(request_token, callback) {
    const TOKEN_URI = GSUITE_AUD
    const data = {
      grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
      assertion: request_token
    }
    axios.post(TOKEN_URI, data)
      .then((res) => {
        console.log(`statusCode: ${res.statusCode}`)
        console.log(res)
        // callback(res)
      })
      .catch((error) => {
        /**
         * Here i get the error 'Invalid JWT signature' and sounds logic
         * since it doesn't know the public key for the RSA certificated
         * private key that i used
         * 
         */
        console.error(error)
      })
  }

  function listUsers(auth) {
    const service = google.admin({
      version: 'directory_v1',
      auth,
    })
    service.users.list({
        customer: 'my_customer',
        orderBy: 'email',
        maxResults: 500,
        query: 'orgUnitPath=/'
      },
      async(err, res) => {
        // Do things once i get the token..
      })
  }

}

export default fetchGSuiteUsersUtil
Run Code Online (Sandbox Code Playgroud)

Joh*_*ley 6

您误解了 Google Cloud Service 帐户和 G Suite 域范围委派。

\n\n
\n

我如何让 google api 知道公钥?

\n
\n\n

你不知道。Google 已经从 Google 作为服务帐户 JSON 文件的一部分提供给您的私钥中知道了公钥。您需要在 Google Cloud Console 中创建一个服务帐户,然后将密钥材料下载为 JSON 文件。您无法创建自己的私钥。

\n\n

此外,由于您尝试使用 Admin API,因此必须遵循几个步骤。阅读以下链接中的文档:

\n\n

执行 G Suite 域范围内的授权

\n\n

我写了这篇文章,解释了使用服务帐户私钥、创建签名 JWT 和交换 OAuth 访问令牌的过程。

\n\n

Google Cloud \xe2\x80\x93 为 REST API 调用创建 OAuth 访问令牌

\n\n

补充一点。在您的代码中,您指定了一个audience. 如果您为令牌指定受众,您将不会获得 OAuth 访问令牌。您将获得一个 OIDC 身份令牌,用于基于身份的授权。一个示例是将身份令牌与 Google Cloud IAP(身份感知代理)结合使用。

\n