【问题标题】:Does signing of the JWT require internet access?签署 JWT 需要互联网访问吗?
【发布时间】:2021-12-13 07:38:05
【问题描述】:

JWT 流程是签署 JWT 并使用 JWT 检索访问令牌。此访问令牌用于调用 Google API。

我们使用 Google 身份验证库来签署 JWT。这个签名过程容器是本地的还是需要互联网访问另一个服务来签署 JWT?

【问题讨论】:

  • 您不仅需要访问 Internet 来请求访问令牌,还需要访问 Internet 才能访问 api。访问令牌是在授权服务器上创建的。因此,要创建一个,您需要能够联系该服务器。此外,API 也在 Web 服务器上运行。
  • 取决于签名私钥的存储位置。你用你的私钥签名,当你将你的 jwt 发送给谷歌以请求 AccessToken 谷歌需要公钥来验证你的 jwt。这是什么流量?这不是通常的 OAuth 2.0 授权之一,是吗?

标签: oauth-2.0 google-api jwt


【解决方案1】:

为了查看使用服务账户获取访问令牌的流程,例如看到使用Javascript获取访问令牌的脚本时,可以在没有web访问的情况下创建jwt的值。但是,当使用 jwt 检索访问令牌时,需要访问 Google 的端点,例如https://www.googleapis.com/oauth2/v4/tokenRef

使用服务帐号获取访问令牌的脚本如下。

const private_key = "###"; // private_key of JSON file retrieved by creating Service Account
const client_email = "###"; // client_email of JSON file retrieved by creating Service Account
const scopes = ["https://www.googleapis.com/auth/drive.readonly"]; // Scopes

const url = "https://www.googleapis.com/oauth2/v4/token";
const header = { alg: "RS256", typ: "JWT" };
const now = Math.floor(Date.now() / 1000);
const claim = {
  iss: client_email,
  scope: scopes.join(" "),
  aud: url,
  exp: (now + 3600).toString(),
  iat: now.toString(),
};
const signature = btoa(JSON.stringify(header)) + "." + btoa(JSON.stringify(claim));
const sign = new JSEncrypt();
sign.setPrivateKey(private_key);
const jwt = signature + "." + sign.sign(signature, CryptoJS.SHA256, "sha256");
const params = {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    assertion: jwt,
    grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
  }),
};
const obj = await fetch(url, params).then((res) => res.json()).catch((err) => console.log(err));
console.log(obj);

参考:

【讨论】:

    猜你喜欢
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    • 2021-09-21
    • 1970-01-01
    • 1970-01-01
    • 2015-01-10
    • 2016-08-21
    • 1970-01-01
    相关资源
    最近更新 更多