使用 ScriptApp.getIdentityToken() 在应用程序脚本中生成令牌时卡住,在 Google Sheet 中给出 Null Token 错误

问题描述 投票:0回答:1
`大家好

我们正在尝试在 Google Sheets 中创建一个自定义函数,该函数将使用 Google App Script 触发云函数

Google Sheet -> 自定义函数 -> Google App 脚本 -> 云函数

使用的云函数是HTTP云函数,将使用

触发

UrlFetchApp.fetch()
由于云功能需要身份令牌,我们在应用程序脚本中使用“ScriptApp.getIdentityToken()”生成身份令牌。
我们希望以登录 Google Sheet 的用户身份调用云函数。如果用户有权调用云函数,则用户应该能够调用云函数并从云函数获取数据,否则必须收到错误。

我们设置了以下范围(如 stackoverflow 上的许多文章和帖子所读)

清单文件:appsscript.json

{ "timeZone": "Asia/Kolkata", "dependencies": { }, "exceptionLogging" : "STACKDRIVER", "runtimeVersion" : "V8", "oauthScopes" : [ "openid" , "https://www.googleapis.com/auth/spreadsheets", "https://www.googleapis.com/auth/script.external_request", "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/spreadsheets.currentonly" ] }
我们将App Script的项目更改为我们的云函数所在的项目。

我们已授予Google Sheet用户调用云函数的权限。事实上,我们已经给了他 Cloud Function Admin 角色(为了使其正常工作!)

问题: 当用户从 Google Sheet 执行自定义函数时,无法创建身份令牌。我们尝试记录并打印令牌。

token = ScriptApp.getIdentityToken(); Logger.log(token); Which gives the output: [error]: Cloud Logs --------------------------------------------------- Feb 1, 2024, 4:46:17 PM Info Token null
因此云函数调用失败并出现以下错误

Exception: Request failed for https://asia-south1-test-project.cloudfunctions.net returned code 401. Truncated server response: <html><head> <meta http-equiv="content-type" content="text/html;charset=utf-8"> <title>401 Unauthorized</title> </head> <body text=#000000 bgcolor... (use muteHttpExceptions option to examine full response) at callCloudFunction(Code:39:30)
但是如果我直接从应用程序脚本运行相同的函数
它打印为 GCP 项目中的 App 脚本项目创建的 OAuth 2.0 客户端 ID 的身份令牌 (JWT)(与 Oauth Consent 屏幕一起创建)。并按预期执行云函数。

尝试过的事情: 创建了一个单独的函数来获取身份令牌;缓存该令牌并在主函数中使用它 使用服务帐户(这是我们最后的手段,因为我们不想使用服务帐户调用云功能)

我们一直被这个问题困扰;如果您能帮助我们,这将造福世界!预先感谢。`

google-sheets google-apps-script google-cloud-functions
1个回答
0
投票
自定义函数不会询问用户权限,也不使用之前授权的范围(

文档)。因此,他们无法使用某些 Google Apps 脚本服务。

文档建议通过自定义菜单使用自定义功能,即需要用户授权的上下文。

© www.soinside.com 2019 - 2024. All rights reserved.