使用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.comfor 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-platformscope 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
subandnameexists in your GCP project.
内容的提问来源于stack exchange,提问作者pythonhmmm

