Authenticating background jobs and workers without user sessions
A job fires at 3 a.m. to reconcile invoices, resize the images someone uploaded an hour ago, or send the weekly digest. There is no browser, no session cookie, no logged-in user—and yet the job needs to act as someone: with the permissions to touch that tenant's data and nobody else's. The lazy answers are the dangerous ones. Teams reach for a god-mode service account that can do anything, or they serialize a user's access token into the queue and hope it hasn't expired by the time the worker picks it up. Both turn your background tier into the softest target in the system.
Why the obvious shortcuts hurt
The all-powerful service account is the one credential an attacker most wants, and the one you can least afford to leak—it's scoped to everything, so a single compromised worker becomes a full breach. Stuffing a user's token into the job payload is worse in a subtler way: queue payloads get logged, retried, dead-lettered, and sat on in storage for hours or days. A short-lived access token that was fine at enqueue time is either expired by the time the worker runs (job fails) or, if you made it long-lived to avoid that, is now a long-lived bearer credential sitting in your message broker's storage. Neither is acceptable.
Separate identity from on-behalf-of context
The clarifying move is to split two things that the shortcuts smash together. There's what the worker is—its own machine identity, used to prove to your auth system that it's an authorized worker. And there's who the work is for—the user or tenant whose data this job touches. The worker authenticates as itself, then exchanges that identity for a narrowly scoped credential to act on behalf of a specific subject, minted fresh at execution time.
What goes in the queue, then, is not a credential at all. It's a reference: which user, which tenant, which action. The authority to act is acquired when the job runs, not when it's enqueued.
{
"job": "invoice.reconcile",
"subject_id": "user_8842",
"tenant_id": "org_221",
"scopes": ["invoices:read", "invoices:write"],
"enqueued_at": "2026-07-07T03:00:00Z",
"trace_id": "01J9ZC..."
}No token, nothing replayable. If this payload leaks, it reveals intent, not access.
Minting the credential at execution time
When the worker dequeues the job, it presents its own machine credential and requests a token scoped to exactly this job's needs—this subject, this tenant, these two scopes, expiring in minutes. This is the OAuth token-exchange shape (RFC 8693): trade a subject reference plus the actor's identity for a downscoped, short-lived token.
async function runJob(job: JobPayload) {
// 1) the worker proves what it is (machine creds: mTLS, SPIFFE SVID, or a client cert)
const workerAssertion = await getWorkerIdentity();
// 2) exchange it for a token scoped to THIS job, minted now, expiring soon
const token = await auth.tokenExchange({
actor: workerAssertion, // "I am worker-pool-7"
subject: job.subject_id, // "acting on behalf of user_8842"
tenant: job.tenant_id,
scopes: job.scopes, // never broader than the job needs
ttl: "5m", // outlives the job, not the night
});
// 3) do the work with a least-privilege, short-lived credential
await invoices.reconcile(job.tenant_id, { token });
// token expires on its own; nothing to revoke, nothing left in the queue
}The TTL is chosen to cover the job plus a margin for retries—minutes, not hours. A credential that expires on its own is one you never have to remember to revoke, and one that's useless to anyone who finds it later.
Rule of thumb for TTL: size it to the 99th-percentile job duration plus one retry, then round up a little—not to the worst case you can imagine. If a job legitimately runs longer than any sane token lifetime (a multi-hour export), have it re-mint mid-run rather than holding a long-lived token the whole time. The goal is that a leaked worker token is stale almost immediately.
Keeping the actor in the audit trail
Here's the detail that separates a mature system from one that passes a demo: when the job writes to the audit log, who did it? If the answer is "the worker," you've lost the thread—every 3 a.m. action looks like it came from a faceless service, and you can't answer "who caused this change?" during an incident. The token exchange above carries both identities, so your audit log should too: the subject (on whose behalf) and the actor (which worker actually executed).
{
"event": "invoice.reconciled",
"subject": "user_8842", // on whose behalf
"actor": "worker-pool-7", // what actually ran it
"via": "job:invoice.reconcile",
"tenant": "org_221",
"ts": "2026-07-07T03:00:12Z"
}Now a reviewer can see that a user's scheduled action was carried out by a specific worker, trace it back to the enqueue, and distinguish a legitimate automated change from a worker that started acting on behalf of users it never should have.
Don't let a job escalate past its enqueuer. A job should never be able to request broader scopes at execution than the context that enqueued it was allowed to grant. If user A enqueues a job, the minted token's scopes must be bounded by A's own permissions at enqueue time—otherwise a low-privilege user who can enqueue jobs can launder themselves into high-privilege actions by naming scopes the worker will dutifully request. Validate the scope request against the enqueuer's authority, not just the worker's.
Giving the worker an identity in the first place
All of this rests on the worker having a real, verifiable machine identity—step one of the exchange. In a container platform that means a workload identity issued and rotated by the platform (a SPIFFE SVID, a cloud instance identity, a mounted short-lived cert), not a static secret baked into the image. A worker that authenticates with a hardcoded API key has just moved the god-mode-credential problem one layer down. The whole chain is only as strong as how the worker proves what it is.
Background work is where auth quietly rots, because there's no user watching and the shortcuts look fine until an audit or a breach. Doing it right—machine identity, execution-time token exchange, bounded scopes, dual-identity logging—needs an identity system that treats services and on-behalf-of context as first-class, not an afterthought bolted onto user login. Owning that layer lets you mint exactly the credential each job needs and trace it end to end; Bastionary's token exchange and actor-aware audit log are built for the 3 a.m. job that has no one logged in.
Run it yourself
Bastionary is free, open-source software. Follow the quick start to have it running on your own server, or browse the releases on Git.