You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Google Apps Script的WebApp用户权限控制问题(Execute as Me)

解决方案:在“以我身份执行”的GAS WebApp中获取访问用户邮箱并实现权限控制

核心方法:利用WebApp事件对象的e.user属性

当WebApp部署为Execute as Me且Anyone with Google Account时,Session.getActiveUser()返回的是部署者身份(或空值),但WebApp的doGet/doPost函数接收的事件对象e中,e.user代表实际访问应用的用户。只要用户用Google账号登录访问,就能通过e.user.getEmail()获取其邮箱ID,完全满足权限验证需求,且无需共享Google表格权限。

具体实现步骤

  1. 存储权限规则

    • 新建一个仅你(部署者)有权访问的Google表格,用于管理用户权限:
      • 表头:邮箱地址、权限等级(可选值:read/write/no)
      • 逐行添加团队用户的邮箱和对应权限
  2. 修改WebApp入口函数
    在doGet或doPost函数中加入身份验证与权限判断逻辑:

    function doGet(e) {
      // 获取访问用户的邮箱
      const userEmail = e.user?.getEmail();
      
      // 验证用户是否登录Google账号
      if (!userEmail) {
        return HtmlService.createHtmlOutput('<h3>请使用Google账号登录后访问</h3>');
      }
      
      // 读取权限配置表格(仅部署者需拥有该表格权限)
      const permissionSheetId = '你的权限表格ID';
      const sheet = SpreadsheetApp.openById(permissionSheetId).getSheetByName('权限列表');
      const permissionData = sheet.getDataRange().getValues().slice(1); // 跳过表头
      
      // 匹配用户权限
      const userPermission = permissionData.find(row => row[0] === userEmail);
      
      // 根据权限返回对应页面或提示
      if (!userPermission || userPermission[1] === 'no') {
        return HtmlService.createHtmlOutput('<h3>你没有访问权限</h3>');
      } else if (userPermission[1] === 'read') {
        return HtmlService.createHtmlOutputFromFile('只读页面');
      } else if (userPermission[1] === 'write') {
        return HtmlService.createHtmlOutputFromFile('读写页面');
      }
    }
    
  3. 部署验证

    • 保持WebApp部署配置:
      • Execute as: Me (你的邮箱)
      • Who has access: Anyone with Google Account
    • 用不同权限的团队账号测试,验证权限控制是否生效

关键注意事项

  • e.user仅在用户以Google账号登录时有效,若部署选项选“Anyone, even anonymous”,e.user会为null,因此必须保持“Anyone with Google Account”配置。
  • 权限表格无需共享给任何用户,脚本以你的身份执行,拥有读取该表格的权限。
  • 该方案无需额外创建API或重构现有代码,仅需在入口函数添加验证逻辑,完全符合“简便方案”的需求。

内容的提问来源于stack exchange,提问作者skpraveen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 18:18:24