Skip to content

Core\Jwt::signObject

Signs an object and returns a JSON Web Token (JWT). The object is a class with #[Core\Json\Derive] or a shape. Its fields become the claims in the token, written as Core\Json::encode writes them. So a claim can be a number, a list or another object, not only text.

The key is always a key pair. The private half signs, and the pair's kind chooses the algorithm. You give the public half to the services that check the token. They check it with Core\Jwt::verifyIssued.

You must give a lifetime. signObject adds two claims itself: iat, the time of signing, and exp, the time the token expires. The object cannot have fields with these two names.

The examples below sign an object and read its claims, sign a list with a key name in the header, and issue an access token that another service checks.

Parameters

  • $claimsobjectA shape, or an object of a class with #[Core\Json\Derive]. It is encoded as a JSON object. This method writes exp and iat, so $claims may not contain them. A value that cannot be encoded as JSON is a bug in the program.
  • $lifetimeCore\Time\DurationHow long the token is valid, such as 15m, 1h or 7d. It must be greater than zero. A token that is already expired is a bug in the program.
  • $keyCore\Crypto\KeyPairA Core\Crypto\KeyPair. It signs with ES256, EdDSA, RS256 or PS256, depending on its kind. A shared secret is not allowed here. A token with these claims is for another service, and Core\Jwt::verify reads only the string claims that sign writes.

Options

  • kidstringoptionalThe key's name, written into the header. Use it when the receiver has several keys. By default there is no kid. The value is written exactly as given. It does not choose which key signs the token.
  • typstringoptionalThe header's typ. It is JWT if you leave it out. RFC 9068's access tokens use at+jwt.
  • embedKeybooloptionalWrites the public key of the pair into the header, as a minimal JWK (RFC 7638). A DPoP proof needs this. It is off by default.

Return value

Returns string. The token as a string, in the same format that sign returns. The payload is the claims object, with iat and exp as its last two fields.

Errors

  • LogicError$claims contains exp or iat. $claims cannot be encoded as JSON, for example a class without #[Core\Json\Derive], a secret value, a bytes value or a cycle. $key is an X25519 pair, which cannot sign. $lifetime is zero or negative.
  • RuntimeErrorThe process does not have enough memory for the token.

Examples

Basics

<?nvs
// Shows how to sign an object into a token with a key pair.
// `#[Core\Json\Derive]` lets `Core\Json` write this class as JSON.
// `signObject` needs this to write the claims.
#[Core\Json\Derive]
final class Claims
{
public string $sub;
public int $level;
public function constructor(string $sub, int $level)
{
$this->sub = $sub;
$this->level = $level;
}
}
// An `Ed25519` key pair has a private half and a public half. The private half signs.
Core\Crypto\KeyPair $pair = Core\Crypto::generateKeyPair(Core\Crypto\KeyKind::Ed25519);
// `signObject` returns the token. It is valid for 15 minutes.
string $token = Core\Jwt::signObject(new Claims('42', 3), 15m, $pair);
// The second part of the token is the payload: the claims as JSON.
// `level` is a number in the payload, not a string. This prints `42` and `3`.
string $payload = Core\Encoding::fromBase64Url(Core\Str::split($token, '.')[1]) as string;
var $claims = Core\Json::decodeAs<{ sub: string, level: int, iat: int, exp: int }>($payload);
echo $claims->sub, "\n";
echo $claims->level, "\n";
// `signObject` adds two claims: `iat` is the time of signing and `exp` is the expiry.
// This prints `900`, the lifetime in seconds.
echo $claims->exp - $claims->iat, "\n";
Output
42
3
900

A list and a key name

<?nvs
// Shows how to sign a claim that is a list, and how to name the key in the token's header.
#[Core\Json\Derive]
final class Grant
{
public string $sub;
public array<string> $roles;
public function constructor(string $sub, array<string> $roles)
{
$this->sub = $sub;
$this->roles = $roles;
}
}
// A `P256` key pair signs with the algorithm `ES256`.
Core\Crypto\KeyPair $pair = Core\Crypto::generateKeyPair(Core\Crypto\KeyKind::P256);
// The `kid` option writes a name for the key into the token's header.
// A service that has several keys uses this name to find the right one.
string $token = Core\Jwt::signObject(new Grant('42', ['editor', 'viewer']), 1h, $pair, { kid: '2026-key' });
array<string> $parts = Core\Str::split($token, '.');
// The first part is the header. This prints `{"alg":"ES256","kid":"2026-key","typ":"JWT"}`.
echo Core\Encoding::fromBase64Url($parts[0]) as string, "\n";
// The second part is the payload. `roles` is a JSON list in it.
// This prints `editor` and `viewer`.
string $payload = Core\Encoding::fromBase64Url($parts[1]) as string;
var $claims = Core\Json::decodeAs<{ sub: string, roles: array<string>, iat: int, exp: int }>($payload);
foreach ($claims->roles as string $role) {
echo $role, "\n";
}
Output
{"alg":"ES256","kid":"2026-key","typ":"JWT"}
editor
viewer

An access token

<?nvs
// Shows an access token: a login server signs it, and another service checks it with the public key.
#[Core\Json\Derive]
final class Access
{
public string $iss;
public string $aud;
public string $sub;
public array<string> $scopes;
public function constructor(string $iss, string $aud, string $sub, array<string> $scopes)
{
$this->iss = $iss;
$this->aud = $aud;
$this->sub = $sub;
$this->scopes = $scopes;
}
}
// The login server keeps the key pair. It gives only the public key to other services.
Core\Crypto\KeyPair $loginServer = Core\Crypto::generateKeyPair(Core\Crypto\KeyKind::Ed25519);
Core\Crypto\PublicKey $published = $loginServer->publicKey();
// `iss` names the server that signed the token. `aud` names the service that may use it.
// `at+jwt` is the standard `typ` for an access token.
string $token = Core\Jwt::signObject(
new Access('https://login.example.com', 'orders-api', '1042', ['orders:read']),
10m,
$loginServer,
{ typ: 'at+jwt' },
);
// This method runs in the orders service. `Core\Jwt::verifyIssued` checks the signature,
// the expiry, `iss` and `aud`. A token that is not valid throws a `RuntimeError`.
class Orders
{
// The claims are `tainted` because they come from outside the program.
public static function user(string $token, Core\Crypto\PublicKey $key): tainted string
{
try {
var $access = Core\Jwt::verifyIssued<
tainted { iss: string, aud: string, sub: string, scopes: array<string>, iat: int, exp: int }
>($token, $key, 'https://login.example.com', 'orders-api');
return 'user ' . $access->sub . ' may use ' . $access->scopes[0];
} catch (RuntimeError $invalid) {
return 'not allowed';
}
}
}
// This prints `user 1042 may use orders:read`.
echo Orders::user($token, $published), "\n";
// A token for a different service has another `aud`. This prints `not allowed`.
string $billing = Core\Jwt::signObject(
new Access('https://login.example.com', 'billing-api', '1042', ['billing:read']),
10m,
$loginServer,
);
echo Orders::user($billing, $published), "\n";
Output
user 1042 may use orders:read
not allowed