The three GCP credentials: whose identity does the request use?
The "Sign in with Google" button on so many sites is OAuth 2.0. Later I needed a server to read a Google Calendar on a schedule, with no user signed in while it runs. Every OAuth request acts for a user who clicked "allow", so to use OAuth the server has to get one person to authorize it once and then keep borrowing that person's identity. That works, until the person revokes access or the token stops working, and then the server can't read the calendar. When the calendar doesn't belong to any user, the app's own identity fits better: a Service Account.
GCP has three credentials, and each one makes requests under a different identity.
| Credential | Whose identity | What it's for |
|---|---|---|
| OAuth 2.0 Client ID | a real user's | let people sign into your app, act on their data |
| Service Account | your app's own | machine to machine, no user involved |
| API Key | nobody's, from browser or backend | call a public Google API like Maps |
To choose, ask in this order:
- A real person has to click "allow" → OAuth 2.0 Client ID.
- A public API like Maps that needs nobody's identity → API Key, even from your backend.
- Your app acts as itself → Service Account.
OAuth 2.0 Client ID: requests made for a user
I hit this building a Google sign-in (the One Tap popup, the kind Medium uses, officially Google Identity Services). It wanted an OAuth 2.0 Client ID. That confused me, because I was already doing Google login through Firebase Auth. Were they different systems?
They aren't. Both are OAuth 2.0 Client IDs underneath. They differ only in plumbing, and both need the user to walk through the sign-in flow. You can even chain them: let One Tap collect the credential, then hand it to Firebase Auth to manage:
// the user actively logs in
google.accounts.id.initialize({
client_id: "YOUR-WEB-CLIENT-ID.apps.googleusercontent.com",
callback: (response) => {
// response.credential is the user's ID token (a JWT), hand it straight to Firebase
firebase.auth().signInWithCredential(
firebase.auth.GoogleAuthProvider.credential(response.credential)
)
},
})Every OAuth request acts for one user. If the app asks for offline access at sign-in, the backend gets a refresh token. After that, the backend can trade it for new access tokens while the user is offline. So once someone has consented, a scheduled backend can keep reading their calendar through OAuth.
The catch is that the server's access now depends on that one person. Google's OAuth documentation lists the cases where a refresh token stops working, such as the user revoking access or the token going unused for six months. If the app's consent screen is still in Testing status, the refresh token expires in seven days. When any of these happens, the server can't read the calendar until that person signs in again.
To create one: GCP Console → APIs & Services → Credentials → Create Credentials → OAuth 2.0 Client ID → pick the application type → set the authorized redirect URIs.
Service Account: a virtual employee
This is the credential for machine to machine work, no human in the loop. A Service Account (SA) is a virtual employee: it has an identity (an email address), and you grant it permissions.
I wanted my backend to read one specific calendar under its own identity, without borrowing any user's authorization, so I used a Service Account.
The flow that finally worked:
- Enable the Calendar API in GCP.
- Create a Service Account, the identity that will call that API.
- Add the SA's email to that calendar's share list.
- Download the SA's JSON key, pull the values into env vars, build the auth client.
I skipped step 3 the first time. Everything else looked correct, and the API kept failing. I tested this with the same SA: a calendar that exists but isn't shared with it, and a calendar that doesn't exist at all, both return 404 Not Found with identical bodies, as Google's Calendar API docs describe. So if the API returns 404, check the share list first.
No amount of GCP permission lets the SA read a calendar that isn't shared with it. Even if you give the SA Owner on the whole project in GCP IAM (Identity and Access Management), the result is the same. Calendar is a Google Workspace API (the Gmail, Calendar and Drive family): read access depends only on the calendar's own sharing settings, and GCP IAM roles don't cover it. If your company uses Workspace, there is one other route: a Workspace super admin turns on domain-wide delegation, which lets the SA act as users in the organization. That setting lives in the Workspace Admin console, also outside GCP IAM.
function getGoogleAuth() {
// these three come out of the downloaded SA JSON
const clientEmail = process.env.GOOGLE_CLIENT_EMAIL
const privateKey = process.env.GOOGLE_PRIVATE_KEY?.replace(/\\n/g, '\n') // mind the newlines
const projectId = process.env.GOOGLE_PROJECT_ID
return new google.auth.GoogleAuth({
credentials: { client_email: clientEmail, private_key: privateKey, project_id: projectId },
scopes: ['https://www.googleapis.com/auth/calendar'],
})
}
export function getCalendar() {
return google.calendar({ version: 'v3', auth: getGoogleAuth() })
}API Key: a permission slip for public stuff
The last one is the simplest. An API Key is for public Google services that don't touch anyone's private data, like Maps.
// no key: HTTP 200, but the body says "status": "REQUEST_DENIED"
fetch(`https://maps.googleapis.com/maps/api/geocode/json?address=Taipei`)
// with key: results come back, billed against your monthly free usage first
fetch(`https://maps.googleapis.com/maps/api/geocode/json?address=Taipei&key=${API_KEY}`)The key isn't really about identity. It's about abuse: rate limits, usage tracking, billing, restricting which sites or apps may use it. An API key on AWS API Gateway serves the same purpose: it lets the provider count how much you use and bill for it.
Putting it together
A typical full stack flow uses all three:
- Frontend logs the user in with OAuth 2.0.
- Frontend passes the user's token to the backend to verify identity.
- Backend uses a Service Account to talk to Google services.
- Need a public service like Maps? Add an API Key.
The decision, checked in this order:
if (aRealUserMustConsent) return 'OAuth 2.0 Client ID'
if (noIdentityNeededLikeMaps) return 'API Key' // even when your backend calls it
return 'Service Account' // your app acting as itselfDo you have to download an SA key?
Step 4 of the flow above downloads the SA's JSON key. By default that key never expires, and if it leaks, it works until someone revokes it.
Deployed on GCP (Cloud Run, GCE, GKE): construct the client without passing a credential, and Google's SDK uses ADC (Application Default Credentials) to look in three places, in order, taking the first one it finds:
- The JSON file pointed to by the
GOOGLE_APPLICATION_CREDENTIALSenv var. - The file left behind by running
gcloud auth application-default loginon this machine. It holds the credential of the person who signed in, not an SA. - The SA attached to where the code runs. GCP machines have a built-in metadata server, and the code can ask it for short-lived tokens for that SA.
// no credentials passed: ADC searches the three places above
const auth = new google.auth.GoogleAuth({
scopes: ['https://www.googleapis.com/auth/calendar'],
})On Cloud Run the first two usually don't exist, so ADC uses the third, and no key file is needed. If you don't name an SA when you deploy, Cloud Run attaches the Compute Engine default SA. For organizations created before 2024-05-03, or projects outside any organization, GCP may have automatically given that default SA the Editor role on the whole project. Anyone who breaks into the service can then use its identity to change most resources in the project. So create your own SA, give it only what it needs, and attach that one.
On your own machine, ADC usually stops at place 2 and uses the developer's own identity. If the developer owns the calendar, local reads always succeed, so a share list missing the SA causes no local error. You only find out after deploying, when the code runs as the SA and the API returns 404. To test locally as the SA, sign in with gcloud auth application-default login --impersonate-service-account SA_EMAIL. Google's impersonation docs state that the developer's account needs roles/iam.serviceAccountTokenCreator on that SA to do this.
Deployed on a platform like Vercel: the machine isn't on GCP, there's no metadata server, and all three ADC places are empty. You have two options: put the key in env vars like the code above, or use Vercel's OIDC (OpenID Connect) federation. With OIDC, the code on Vercel gets a token signed by Vercel and exchanges it with GCP for a short-lived SA token, with no key anywhere.
Before GCP issues that token it checks two things, so set both up first:
- Was the token signed by a source GCP trusts? Create a Workload Identity Federation in GCP that trusts Vercel.
- May this Vercel project use this SA? The federation turns the team, project and environment written in the token into an identity GCP recognizes (a principal), for example
principal://iam.googleapis.com/projects/123456/locations/global/workloadIdentityPools/vercel/subject/owner:my-team:project:my-app:environment:production. Grantroles/iam.serviceAccountUseron the SA to that principal.
The full setup steps are in Vercel's docs.
Compared with AWS
AWS and GCP wire up service permissions from opposite ends.
On AWS, nothing has access until you grant it. Create a Lambda in the console and, by default, it gets its own new execution role with only the basic logging permissions, like CreateLogStream and PutLogEvents. A second Lambda gets its own separate role by default, even if the permissions are identical. You are always the one saying "this function may touch that service."
GCP hands out permission by default. Every Cloud Run service you deploy without naming a service account shares the same Compute Engine default SA, and that SA may hold Editor on the whole project. With Editor, the service can read and write most GCP resources in the project with no extra grant. But Editor is a GCP IAM role, so to read a calendar the SA still has to be added to that calendar's share list.