跳到正文
DEV Community· Mango Developer·· 53 分鐘前AI 評分62

如何以 Google Cloud 免金鑰驗證取代共用 AI Studio API 金鑰

How to Replace Shared AI Studio API Keys With Keyless Google Cloud Auth

AI 導讀

Google Cloud 的 Sergio Villani 提供一套約 20 分鐘的遷移指南,建議以 Application Default Credentials(ADC)及服務帳戶取代共用 Google AI Studio API 金鑰。

正文

Almost every AI prototype begins the same way: a developer grabs an API key from Google AI Studio, drops it into a local .env file, and gets a working demo running in five minutes. That speed is great during week one, yet trouble starts the moment the prototype gains real users and that same key gets copied into a team Slack thread, a CI pipeline, or a production server config.

By the time a startup has five engineers and a staging environment, there is rarely just one key. Every developer has personal keys sitting in shell profiles, and the application itself ships with a shared key baked into its configuration. If one of those bearer tokens lands in a public GitHub repository or a mobile app bundle, automated scrapers find it within minutes and burn tens of thousands of dollars before the first billing alert fires. Under cloud shared-responsibility rules, the customer still owes the bill for valid API calls made with their own credentials.

On November 21, 2026, Google Cloud's Sergio Villani published a practical DevOps guide showing how teams can retire raw AI Studio keys completely in about 20 minutes without slowing down local development.

Why raw bearer keys fail production DevOps standards

An AI Studio key is a bare bearer token: anyone who possesses the string can spend against it. By default, it does not expire automatically, it is not bound to a specific developer laptop or container workload, and it has no hard spending ceiling unless you configure one manually. Worse, when an engineer leaves the company, nobody has a clean inventory of which shared keys they touched.

Google's guide flags three clear triggers for migrating immediately: if any key has left your laptop (via chat, git history, or a server deploy), if more than one person on the team calls the API, or if your monthly spend exceeds a few hundred dollars ahead of customer onboarding.

Before rotating anything, run a quick scan across your repositories to locate hardcoded credentials. Google's companion repository includes a lightweight scanner (python -m step1_keyless_auth.scan_for_keys run on the repository root) that flags Google API key patterns and literal api_key= assignments by file and line number without printing the secret itself, exiting non-zero so you can drop it straight into CI. Running that check as a pre-commit hook or pull-request gate prevents new bearer tokens from sneaking back in after cleanup.

Diagram of cloud computing architecture connecting laptops and mobile devices to analytics services

Expand

Diagram of cloud computing architecture connecting laptops and mobile devices to analytics services

Image: Srv Ganesh via Wikimedia Commons, CC BY-SA 4.0

Step 1 and 2: Give every developer a single keyless login

Instead of handing out static keys, each developer runs two commands locally:

BashCopy

gcloud auth application-default login
export GOOGLE_CLOUD_PROJECT=my-startup-dev

Signing in through the browser stores a short-lived Application Default Credential (ADC) on the machine. Every official Google Cloud SDK discovers that credential automatically, leaving zero static keys in .env files or shell configs.

Better yet, that same login works across first-party and partner models in Model Garden so your team does not juggle separate vendor keys or separate invoices. Switching an existing Google Gen AI SDK prototype off a hardcoded api_key argument takes a single client parameter change (enterprise=True, which older samples write as vertexai=True):

PythonCopy

from google import genai
client = genai.Client(enterprise=True, project="my-startup-dev", location="global")
resp = client.models.generate_content(model="gemini-4-hydrogen", contents="Hi")
print(resp.text)

With the exact same gcloud login, developers can call Anthropic's Claude models via AnthropicVertex (such as claude-sonnet-5-5) after enabling the model card once per project, or call open-weight models like openai/gpt-oss-120b-maas through the OpenAI SDK by refreshing a one-hour OAuth token from google.auth.default. OpenAI's GPT-6 models also entered private preview in Model Garden in October 2026 under the same authentication path, and consolidating every model call onto one cloud invoice makes it straightforward to compare cost and latency across providers.

Step 3 and 4: Isolate production apps with service accounts and narrow IAM

Developer logins belong on laptops in a dev project (my-startup-dev), never inside production containers. For deployed services on Cloud Run, GKE, or Compute Engine, attach a dedicated service account to the workload. Your Python or Node application code stays identical because ADC automatically picks up a short-lived, roughly one-hour token for the attached service account at runtime.

BashCopy

gcloud iam service-accounts create agent-runtime --display-name="Runtime identity for the app"
gcloud run deploy my-agent --image=us-docker.pkg.dev/my-startup-prod/agents/api:v1 --service-account=agent-runtime@my-startup-prod.iam.gserviceaccount.com --region=us-central1

Separating my-startup-dev from my-startup-prod ensures a runaway test loop on an engineer's laptop cannot exhaust production quotas. Next, lock down permissions using roles/aiplatform.user rather than broad Editor or Owner roles. Grant that single role to a Google Group (such as group:ai-builders@my-startup.com) in dev so offboarding someone requires only removing them from the group, and grant it directly to the agent-runtime service account in production.

If your project sits inside a Google Cloud Organization, add three extra guardrails before launch. First, apply the vertexai.allowedModels policy to restrict projects to approved endpoints such as publishers/google/models/gemini-4-hydrogen:predict. Second, run an IAM audit script to verify no service account holds Owner or Editor permissions. Third, enforce Organization Policies denying CREATE on apikeys.googleapis.com/Key and enabling iam.managed.disableServiceAccountKeyCreation so engineers cannot generate new API keys or export downloadable service-account JSON files.

Comparing static AI Studio keys against Google Cloud keyless auth

Migrating from raw bearer keys to identity-based access changes how your team handles rotation, billing attribution, and incident response. The table below summarizes the operational differences across each control layer.

Security and Ops control Raw AI Studio API key Keyless ADC and Service Accounts
Credential lifetime Permanent until manually deleted Short-lived tokens (~1 hour), auto-refreshed
Offboarding a teammate Must hunt down and revoke every shared key Remove user from one Google Group
Blast radius if leaked Full quota spend with no user attribution Scoped to one narrow role and one project
Multi-model access Separate keys and billing for Gemini vs. partners Single credential for Gemini, Claude, and open models
Audit trail Anonymous bearer usage Named user or service account in Cloud Audit Logs
Automated cost cutoff Alerts only unless manually capped Preview spend-cap budgets pause requests automatically

Seeing those trade-offs side by side makes it obvious why teams outgrow AI Studio keys as soon as a second engineer joins the repository.

Cloud computing server hardware in a data center aisle

Expand

Cloud computing server hardware in a data center aisle

Image: Simonebrunozzi via Wikimedia Commons, CC BY 3.0

Step 5: Move remaining third-party keys into Secret Manager and add spend caps

Some external credentials, like Stripe, Slack, or transactional email tokens, cannot use Google Cloud IAM. Store those inside Secret Manager instead of .env files, feeding secrets via standard input (--data-file=-) so values never linger in shell history:

BashCopy

gcloud secrets create stripe-test-key --data-file=-
gcloud secrets add-iam-policy-binding stripe-test-key --member="group:ai-builders@my-startup.com" --role="roles/secretmanager.secretAccessor"

Keep test secrets in dev readable by the developer group, and keep live keys in production readable solely by the agent-runtime service account via SecretManagerServiceClient at startup. Rotating a third-party secret becomes a matter of adding a new secret version without redeploying containers or distributing files over chat. Once everything runs on Secret Manager and ADC, visit aistudio.google.com/apikey and delete every legacy key that ever left a laptop, because migrated keys stay live until explicitly deleted.

To backstop billing surprises, Google Cloud now offers preview spend-cap budgets for Agent Platform, the Gemini API, Cloud Run, and Cloud Run functions. Unlike standard budget emails that notify you while charges keep climbing, a spend-cap budget automatically pauses new requests to that specific service in that project once estimated spend crosses your threshold, sending alerts at 50%, 80%, and 100%.

Know two caveats before relying solely on spend caps: enforcement runs on estimated cost rather than instant real-time metering (so set your cap comfortably below your maximum pain threshold), and lifting a tripped cap can take up to an hour for service recovery while also pausing committed-use workloads. Pair spend caps with tightened Agent Platform quotas so a buggy agent loop hits a rate ceiling well before your billing limit.

Adding runtime guardrails and audit trails before launch

Once every person and workload authenticates with a named identity, two runtime protections become immediately useful. First, Model Armor screens user prompts and model outputs for prompt injection, jailbreak attempts, malicious URLs, and sensitive data before requests ever reach your backend tools. Second, if your product lets a model write and execute Python to analyze user files, use the Gemini API's managed code-execution sandbox (types.ToolCodeExecution) so generated code runs isolated from your application's environment variables, filesystem, and database credentials.

Finally, enable Security Command Center and Cloud Audit Logs across both projects. Because every request now carries a named developer identity or service account rather than an anonymous API key, anomalous API calls or unfamiliar outbound hosts show up with clear ownership during enterprise customer security reviews.

Your 20-minute migration checklist

You do not need a multi-sprint security overhaul to close this gap. Block off 20 minutes with your engineering team and run through the sequence in order:

  1. Run the key scanner across every active repository and delete any literal keys from .env templates.
  2. Have every engineer run gcloud auth application-default login and grant roles/aiplatform.user to a single team Google Group in your dev project.
  3. Deploy production workloads with a dedicated roles/aiplatform.user service account and move remaining Stripe or Slack keys into Secret Manager.
  4. Set a spend-cap budget on both dev and prod projects, enable Cloud Audit Logs, and delete every legacy AI Studio key at aistudio.google.com/apikey.

Once those four steps are done, your developers keep the exact same prototyping speed across Gemini, Claude, and open models without leaving a single bearer token lying around in git history.

For teams already running CI/CD pipelines on GitHub Actions or GitLab, pair this migration with Workload Identity Federation instead of exporting static service-account keys into repository secrets. That keeps build and deployment runners completely keyless from laptop commit to production Cloud Run rollout.

Audit your production service-account permissions quarterly using the repository's IAM check script, and verify that spend-cap alerts route to an active on-call channel rather than an unmonitored billing inbox.


Originally published on Mango Developer.

來源:DEV Community · dev.to