Service tokens
Service tokens are short-lived HS256 JWTs one back-end service presents to another. Each is pinned to scope = service and locked to a named sender (iss) and recipient (aud):
use RoundlyConsulting\Jwt\Facades\Jwt;
$token = Jwt::services()->issue('target-service')->token;
// Or attach one to an outbound internal HTTP call:
Jwt::services()->request('target-service')
->post('https://target.internal/endpoint', [...]);
// On the receiving side, behind `auth:service` (a `service-jwt` guard):
Jwt::services()->claims()?->string('iss'); // the calling serviceAn issued token carries iss (service.issuer), aud (the argument, else service.audience), iat, nbf, exp, jti and scope = service, and lives service.ttl seconds — 60 by default. Issuing with no resolvable audience or an empty own issuer raises ServiceAuthMisconfigured: an unaddressable or anonymous token is never minted.
Extra claims
issue() takes an optional array of extra claims — for example context for a worker acting on the holder’s behalf. Registered names are rejected rather than silently overwritten:
// Extra, non-registered claims travel with the token:
Jwt::services()->issue('notifications', ['job' => 'nightly-sync']);
// A registered name (iss, aud, iat, nbf, exp, jti, scope, sub,
// permissions, tv, email, email_verified) is rejected, not merged:
Jwt::services()->issue('notifications', ['aud' => 'billing']); // throws ServiceAuthMisconfiguredPer-call ttl and subject
Since 2.1.0 issue() takes two named options, for a token bound to one unit of work — one token per AI agent run, bound to the run, living minutes, revoked when the run ends:
use Carbon\CarbonInterval;
use RoundlyConsulting\Jwt\Facades\Jwt;
$issued = Jwt::services()->issue(
claims: ['person' => $person->id, 'company' => $company->id],
ttl: CarbonInterval::minutes(15), // or 900
subject: "agent-run:{$run->id}",
);
// ...when the run ends:
Jwt::logout($issued); // denylists $issued->jti until it expires- ttl overrides service.ttl for this token: an int (seconds) or any DateInterval, CarbonInterval included. It must be whole seconds from 1 to service.max_ttl (default 3600, JWT_SERVICE_MAX_TTL); zero, negative, fractional or over-the-cap values throw ServiceAuthMisconfigured. An interval is measured from a fixed instant, so the same interval always means the same number of seconds. The cap binds only the per-call value, never the operator’s own service.ttl.
- subject sets the sub claim: non-empty, at most 255 bytes of valid UTF-8, no control characters and no leading or trailing whitespace. Anything else throws ServiceAuthMisconfigured; the message names the problem, never the value.
- sub stays a reserved claim: issue(claims: ['sub' => …]) is still refused, so sub is never set by accident — for example by forwarding a request body into $claims. The explicit option is the only way in.
- Every service token carries a jti (a random UUID), with or without the options, so every one is revocable. ServiceTokenIssued carries the subject.
- The options need a bound issuer implementing ServiceTokens\Contracts\ServiceTokenIssuerWithOptions (NativeServiceTokenService does). A host issuer without it keeps working for issue($audience, $claims), but a call with ttl or subject throws ServiceAuthMisconfigured::issuerLacksOptions() rather than drop the options silently. The two contracts merge in 3.0.
- Under Jwt::fake() the options run for real and are recorded: assertServiceTokenIssued('opernity', fn (Claims $c) => $c->get('sub') === 'agent-run:1').
A service token never authenticates as a user. Its sub names what the call is about, for the receiving service to read — not an identity. The jwt guard pins RS256 and scope = access, so it refuses an HS256 scope = service token before reading sub, in provider and claims mode alike, even when the sub is a real user’s key. On the service-jwt guard the identity stays the calling service: ServiceIdentity::getAuthIdentifier() is the iss and ServiceIdentity::subject() returns the sub, or null. A subject may use any naming scheme; a prefix such as agent-run: only makes logs easier to read.
Outbound calls
Jwt::services()->request() and authenticate() attach a freshly issued token as a bearer credential to Laravel’s HTTP client:
use Illuminate\Support\Facades\Http;
use RoundlyConsulting\Jwt\Facades\Jwt;
// A new pending request already carrying a fresh token for the audience.
$response = Jwt::services()->request('notifications')
->post('https://notifications.internal/send', $payload);
// Or attach a token to an existing pending request.
$pending = Http::baseUrl('https://notifications.internal')->acceptJson();
$response = Jwt::services()->authenticate($pending, 'notifications')->post('/send', $payload);- request(?string $audience = null) — a new PendingRequest already carrying a fresh token.
- authenticate(PendingRequest $request, ?string $audience = null) — attach a fresh token to an existing pending request.
Choosing a secret mode
With one shared secret, possession of the secret is the only proof — any holder can mint a token claiming any iss, so the issuer allow-list is a label, not authentication:
# Shared mode: one secret for the whole mesh (openssl rand -base64 48).
SERVICE_JWT_SECRET=<secret>For real service identity, give each service its own secret. The verifier picks the secret by the token’s iss — a kid-style lookup — so a forged iss selects a secret its signature cannot match, and one leaked secret no longer impersonates the whole mesh:
# Per-issuer mode (recommended): overrides SERVICE_JWT_SECRET when set.
SERVICE_JWT_SECRETS="billing:<secret>,api:<secret>"Each issuer appears in the map once: a repeated issuer (compared after trimming, case-sensitive, like the token’s iss) throws JwtMisconfigured when the service is resolved, instead of letting the last pair win. The message never prints a secret — it names the issuer only when it looks like one (^[A-Za-z0-9][A-Za-z0-9._-]*$ and under 32 bytes), otherwise just the colliding entries’ positions (“entries 2 and 5 name the same issuer”), so a pair written secret:issuer stays hidden. A host whose map repeats an issuer fails at boot until it keeps one entry per issuer.
In per-issuer mode the issuing app’s own service.issuer must appear in the map, or issuing raises ServiceAuthMisconfigured. An inbound issuer absent from the map is always rejected as InvalidSignature, even when service.issuers allow-lists it. Its HMAC check still runs, against a random key drawn per service instance, so it costs the same work and fails with the same error as a bad signature — configured issuer names can’t be enumerated, and no learnable key ever lets an unknown issuer through.
Receiving service tokens
Inbound tokens must be addressed to this service’s own name — jwt.service.name, set with JWT_SERVICE_NAME. Unset, it falls back to config('app.service'), then to a slug of APP_NAME; set it explicitly to a stable identifier, because renaming the app would otherwise re-pin the service and break every caller:
# This service's own name — the aud every inbound service token must carry.
JWT_SERVICE_NAME=notifications
# Optional inbound allow-list; empty accepts any issuer.
JWT_SERVICE_ISSUERS=billing,apiVerification requires a valid HS256 signature, scope = service, aud equal to the service name, a non-empty iss and — when service.issuers is set — an iss on that allow-list. Wire the guard and read the calling service:
// config/auth.php
'guards' => [
'service' => ['driver' => 'service-jwt'],
],
// routes
Route::middleware('auth:service')->post('/send', SendController::class);
// inside the controller
$caller = $request->user('service'); // ServiceIdentity
$caller->getAuthIdentifier(); // the calling service's 'iss'
$caller->subject(); // the token's 'sub', or null (2.1.0)
$caller->claims(); // the full Claims bag
Jwt::services()->claims(); // the same claims, through the facade
auth()->guard('service')->payload(); // …or straight from the guardOr verify explicitly:
$claims = Jwt::services()->verify($jwt);
$claims = Jwt::services()->verify($jwt, checkDenylist: true); // also refuse a revoked tokenRevoking a service token
Revocation by jti works exactly as for user tokens, on the same denylist: Jwt::logout($issued), Jwt::denyClaims($claims) or Jwt::denylist()->deny($jti, $until). The entry lives until exp + jwt.leeway, so it covers a per-call ttl too. It is enforced where you ask for it: Jwt::services()->verify($jwt, checkDenylist: true) throws TokenRevoked for a revoked token and — failing closed — ClaimMismatch for a token without jti; the plain verify($jwt) does not consult the denylist.
The service-jwt guard checks too when check_denylist is on — off by default, so existing guards behave as before and a mesh that never revokes needs no denylist store. Turn it on globally with service.check_denylist (JWT_SERVICE_CHECK_DENYLIST) or per guard; the per-guard value wins, and both are read strictly. A revoked token, or one without jti, then gives a null user (401). ServiceGuard::checksDenylist() reports the effective setting:
// config/auth.php — or globally with JWT_SERVICE_CHECK_DENYLIST=true
'guards' => [
'service' => ['driver' => 'service-jwt', 'check_denylist' => true],
],A missing, too-short, single-repeated-byte or PEM-shaped secret, or no resolvable service name, raises ServiceAuthMisconfigured — a 500, never a silent 401.
Show your open-source love
This package is free and MIT-licensed. If it saves you time, a one-off donation or a Patreon membership keeps it maintained, tested and documented.
More ways to support, including cryptoBy donating, you agree to our donation terms.
Want this built into your product?
We integrate our packages into custom Laravel and AI builds. Tell us what you're working on and we'll reply within 48 hours.