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

使用Python服务账号访问IAP保护端点遇401错误(azp/sub不匹配)

问题:使用服务账号访问IAP保护的GKE应用返回401错误

我尝试用GCP官方Python库结合服务账号凭据,访问受IAP保护的GKE应用,代码取自Google官方示例:

from google.oauth2 import id_token
from google.auth.transport.requests import Request

open_id_connect_token = id_token.fetch_id_token(Request(), client_id)

requests.request(
  "GET",
  "https://myapp.com",
   headers={"Authorization": "Bearer {}".format(open_id_connect_token)}
)

其中client_id是IAP使用的OAuth客户端ID(格式类似8xxxxxxxxx.apps.googleusercontent.com),GOOGLE_APPLICATION_CREDENTIALS环境变量已指向服务账号的JSON密钥文件,且该服务账号拥有访问此IAP保护应用的IAM权限。

我通过gcloud iap settings set SETTING_FILE --project=my-project配置了IAP设置,SETTING_FILE内容如下:

access_settings:
  oauth_settings:
    programmatic_clients: ["8xxxxxxxxx.apps.googleusercontent.com"]

操作流程主要遵循官方指南,但预期的2xx响应未出现,实际返回401错误:

Invalid IAP credentials: Service Account doesn't match the authorized party for this application.
('sub' claim (1yyyyyyyyyyyyy) doesn't match expected value (sa-name@project.iam.gserviceaccount.com))

其中1yyyyyyyyyyyyy是服务账号JSON文件中的client_id属性。Python库生成的Token payload如下:

{
  "aud": "8xxxxxxxxx.apps.googleusercontent.com",
  "azp": "sa-name@project.iam.gserviceaccount.com",
  "email": "sa-name@project.iam.gserviceaccount.com",
  "email_verified": true,
  "exp": 1696584237,
  "iat": 1696580637,
  "iss": "https://accounts.google.com",
  "sub": "1yyyyyyyyyyyyy"
}

我尝试了以下操作但问题未解决:

  • 使用不同服务账号(包括IAP所在项目的账号)
  • 尝试将服务账号的client_id添加到access_settings.oauth_settings.programmatic_clients,但被gcloud命令拒绝
  • 在gcloud iap settings set命令中使用不同参数,如--resource-type、--organization、--service
  • 查看Python源码尝试修改Token payload

请问如何获取能被IAP接受的服务账号Token?


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 13:52:40