Flutter集成Google Secret Manager遇403权限问题排查
已从Google Cloud下载服务账号JSON文件并存储在assets文件夹中,且已在Google Cloud项目中为该账号启用「Secret Manager Secret Accessor」和「Secret Manager Viewer」权限,但运行以下代码时出现403权限拒绝错误:
const String secretsPath = 'projects/"project-id"/secrets/smtp_password/versions/latest'; final credentials = json.decode(await rootBundle.loadString('assets/json/google-service-account.json')); final AutoRefreshingAuthClient client = await clientViaServiceAccount( ServiceAccountCredentials.fromJson(credentials), [SecretManagerApi.cloudPlatformScope], baseClient: http.Client()); final SecretManagerApi api = SecretManagerApi(client); final AccessSecretVersionResponse secrets = await api.projects.secrets.versions.access(secretsPath); final String decoded = utf8.decode(base64Url.decode(secrets.payload!.data!));
错误信息:
"DetailedApiRequestError(status: 403, message: Permission 'secretmanager.versions.access' denied for resource 'projects/"project-id"/secrets/smtp_password/versions/latest' (or it may not exist)."
可能的遗漏配置及解决方法
移除secretsPath中的多余引号:代码中
projects/"project-id"的双引号是无效的,正确路径格式应为projects/你的实际项目ID/secrets/smtp_password/versions/latest,引号会导致资源路径识别错误,进而触发权限检查失败。确认服务账号的角色绑定对象:确保「Secret Manager Secret Accessor」角色是直接添加到当前使用的服务账号上,而非用户账号或其他无关账号。可在Google Cloud控制台的IAM页面,找到对应服务账号查看已分配角色列表。
验证服务账号JSON的有效性:检查assets文件夹中的JSON文件是否属于有权限的服务账号,确认文件未过期、未被替换为其他项目的服务账号凭证。
确认Secret资源的存在性:核实
projects/你的实际项目ID/secrets/smtp_password这个Secret确实存在,且latest版本未被禁用或删除。可在Secret Manager控制台查看该Secret的状态和版本信息。检查API Scope配置:虽然
SecretManagerApi.cloudPlatformScope已包含Secret Manager的访问权限,但可尝试显式添加SecretManagerApi.secretManagerScope到权限范围列表中,确保授权范围覆盖所需操作。
内容的提问来源于stack exchange,提问作者Chloé

