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

AWS Cognito谷歌认证:获取Refresh Token及添加API权限域问题

问题描述

我用以下代码通过谷歌认证在AWS Cognito用户池创建新用户:

import { Auth } from 'aws-amplify';    

Auth.federatedSignIn({ provider: "Google" })

创建用户后调用Google Sheets API时遇到两个问题:

  1. 已在Cognito控制台的谷歌选项卡中将access_token和refresh_token映射到自定义属性,但调用Auth.currentAuthenticatedUser()只能拿到access_token,拿不到refresh_token。access_token过期后,虽然还能登录访问AWS API,但无法访问谷歌API,必须重新登录。
  2. 就算拿到access_token,也没法添加调用目标API所需的权限域。默认权限域如下:
"scope": [
    "phone",
    "email",
    "openid",
    "profile",
    "aws.cognito.signin.user.admin"
],

添加https://www.googleapis.com/auth/spreadsheets.readonly到支持的权限域时,会报错:

Error handling auth response. Error: invalid_scope
解决方案

问题1:获取不到Google Refresh Token

要拿到Google的refresh_token,得做好以下几点:

  • 配置Google OAuth应用:在Google Cloud控制台的OAuth 2.0客户端设置里,勾选「启用离线访问」,这样认证时才会返回refresh_token。另外,用户第一次授权才会返回refresh_token,后续重复授权默认不返回,需添加prompt=consent参数强制用户重新授权。
  • 调整Cognito身份池设置:在Cognito用户池的谷歌身份提供商配置中,除了映射refresh_token到自定义属性,还要在「授权范围」里加入offline_access——这是Google返回refresh_token的必要权限。
  • 修改Amplify调用代码:调用Auth.federatedSignIn时,指定包含offline_access和Google Sheets权限的scope,示例如下:
Auth.federatedSignIn({
  provider: "Google",
  options: {
    scope: ["openid", "email", "profile", "offline_access", "https://www.googleapis.com/auth/spreadsheets.readonly"]
  }
})
  • 正确获取用户属性:调用Auth.currentAuthenticatedUser({ bypassCache: true })获取最新用户属性,避免缓存导致拿不到refresh_token。Cognito会把第三方的refresh_token存在你设置的自定义属性里(比如custom:google_refresh_token),需要从用户的attributes字段中提取。

问题2:添加Google Sheets权限域时报invalid_scope错误

这个错误是因为权限域配置位置错误,不能直接在Cognito用户池的「支持的权限域」里添加Google API权限,正确操作如下:

  • 在Google Cloud控制台配置授权范围:打开你的Google OAuth客户端ID设置页面,在「已授权的范围」中添加https://www.googleapis.com/auth/spreadsheets.readonly并保存。
  • 在Amplify调用中指定scope:参考问题1的代码示例,调用Auth.federatedSignIn时直接在options.scope里包含Google Sheets的权限域,Cognito会自动把这些scope传递给Google完成授权。
  • 不要在Cognito用户池添加第三方API scope:Cognito的「支持的权限域」字段仅用于自身OAuth范围,第三方身份提供商的scope需要在调用授权时指定,或在对应平台(如Google Cloud)配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 17:50:23