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

使用Google默认服务账号凭证生成SignedJWT令牌时遭遇403权限错误的技术问询

Alright, let's break down why you're hitting that 403 error and how to fix it. The core issue here is that your default service account doesn't have the necessary permissions to sign JWTs for the target service account. Here's what you need to do:

1. Fix the Permission Issue

The iam.serviceAccounts.signJwt permission required for this operation is granted via the Service Account Token Creator IAM role. You need to assign this role to your default service account, allowing it to perform signJwt operations on the target service account (somekey@someproject.iam.gserviceaccount.com).

Follow these steps in the Google Cloud Console:

  • Navigate to IAM & Admin → IAM
  • Locate your default service account (it typically follows a format like PROJECT_NUMBER-compute@developer.gserviceaccount.com for Compute Engine, or matches the default SA of your environment like Cloud Run/Cloud Functions)
  • Click the pencil icon to edit the account's roles
  • Click Add another role, search for Service Account Token Creator, select it, and save changes
  • Wait 1-5 minutes for IAM permissions to propagate (Google Cloud can take a short time to apply role changes)

2. Correct Code Using Default Credentials

Your code is nearly right—here's the refined version with proper default credential setup:

import time
import json
import google.auth
from googleapiclient.discovery import build

# Get default credentials with the required scope
credentials, your_project_id = google.auth.default(
    scopes=["https://www.googleapis.com/auth/cloud-platform"]
)

now = int(time.time())
expires = now + 900  # 15-minute expiry (max allowed for signJwt)
payload = { 
    'iat': now, 
    'exp': expires, 
    'sub': 'somekey@someproject.iam.gserviceaccount.com', 
    'aud': 'your-target-audience'  # Replace with actual audience (e.g., API URL)
}
body = {'payload': json.dumps(payload)}
name = 'projects/someproject/serviceAccounts/somekey@someproject.iam.gserviceaccount.com'

# Build IAM client with default credentials
iam = build('iam', 'v1', credentials=credentials)
request = iam.projects().serviceAccounts().signJwt(name=name, body=body)
resp = request.execute()
jwt = resp['signedJwt']

print(jwt)

Key Notes:

  • The cloud-platform scope includes all necessary permissions for IAM operations like signJwt, so we don't need to specify a narrower scope here.
  • Replace 'your-target-audience' with the actual intended audience for your JWT (e.g., the URL of the API you plan to authenticate with this token).
  • Ensure the target service account in sub and name exists in your GCP project.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 20:27:54