将 Google Apps Script Web 应用限制为仅供某些用户使用

Limiting Google Apps Script Web app to certain users only

制作一个网络应用程序来更改我的 Google 驱动器上的某些(表格)文件(即用户将像我一样使用该应用程序),但我想限制网络应用程序访问 只对某些用户。部署应用程序时,我只能选择将其设为私有或 public。 一种解决方案是使用会话 class 查看是否有正确的用户登录。

function onAppBegin(){

 if (Session.getActiveUser().getEmail() != "correctappuser@gmail.com") return null;
 accessGranted();
}

但是,我担心这种粗暴的方法是否真的安全且不可破解?

该方法太安全:没有人可以访问。如果您的 Web 应用程序是使用 "Execute the app as: me" 选项部署的,那么 Session.getActiveUser().getEmail() 可能会 return 空字符串。参见 documentation

The circumstances in which the email address is available vary: for example, the user's email address is not available in any context that allows a script to run without that user's authorization, like [...] a web app deployed to "execute as me" (that is, authorized by the developer instead of the user). However, these restrictions generally do not apply if the developer and the user belong to the same G Suite domain.

问题是,即使用户登录访问网络应用程序,他们也没有授权它代表他们做任何事情,例如,找到他们的电子邮件地址。

如果 Web 应用程序部署为由 "User accessing the web app" 执行,那么他们将被要求授权,因此 Web 应用程序可以了解他们的身份。但是,它将只能修改那些用户已经可以直接修改的文件。

我克服这个困难的方法是给授权用户一个网络应用程序的密钥(一些长的随机字符串)。他们通过转到 https://..../exec?key=mykey 访问应用程序,应用程序按如下方式检查密钥:

function doGet(e) {
  if (e.parameter.key == "mykey") {
    var ss = SpreadsheetApp.openById("spreadsheet Id");  
    // modify the spreadsheet
  }
}

现在,这比您原来的方法更粗糙,但它确实有效。如果错误的人获得了密钥,他们将能够使用该应用程序,但损害将仅限于该应用程序的功能。这并不像有人访问您的 Google 帐户那么糟糕。