Core\Jwt::sign
Core\Jwt::sign(
array<string> $claims,
Core\Time\Duration $lifetime,
secret bytes|Core\Crypto\KeyPair $key,
{kid?: string, typ?: string, embedKey?: bool},
): stringSigns a list of claims and returns a JSON Web Token (JWT). A claim is a name and a text value, such as a user id or a role. The token is a short string you can send in a cookie, a header or a URL. Anybody can read the claims in it, but nobody can change them without the key.
The key chooses the algorithm. A secret key of 32 bytes or more signs with HS256, and your own program checks the token with Core\Jwt::verify. A key pair signs with the algorithm of its kind, and other services check the token with the public half.
You must give a lifetime. sign adds two claims itself: iat, the time of signing, and exp, the time the token expires. You cannot write these two claims yourself.
The examples below sign and read back a token, sign with a key pair and a key name, and check a login cookie on each request.
Parameters
$claimsarray<string>The claims for the token, by name. This method writesexpandiat, so$claimsmay not contain them. Every other claim goes into the token unchanged.$lifetimeCore\Time\DurationHow long the token is valid, such as15m,1hor7d. It must be greater than zero. A token that is already expired is a bug in the program.$keysecret bytes|Core\Crypto\KeyPairA shared secret of at least 32 bytes, which signs with HS256.Core\Crypto::generateKey()returns one. A longer secret that you share with another service also works. The key can also be aCore\Crypto\KeyPair. It signs with ES256, EdDSA, RS256 or PS256, depending on its kind. There is no algorithm parameter, because the key decides the algorithm.
Options
kidstringoptionalThe key's name, written into the header. Use it when the receiver has several keys. By default there is nokid. The value is written exactly as given. It does not choose which key signs the token.typstringoptionalThe header'styp. It isJWTif you leave it out. RFC 9068's access tokens useat+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. With a shared secret it throws an error, because a secret has no public key.
Return value
Returns string. The token as a string: a header, a payload and a signature in base64url, joined by two dots. You can put it in a header, a query string or a JSON body without escaping.
Errors
LogicError$keyis a secret shorter than 32 bytes, or anX25519pair, which cannot sign.{ embedKey: true }is used with a shared secret.$lifetimeis zero or negative.$claimscontainsexporiat, or an entry without a name.RuntimeErrorThe process does not have enough memory for the token.
Examples
Basics
<?nvs// Shows how to sign a few claims into a token and read them back.
// `Core\Crypto::generateKey` returns 32 random secret bytes. They are the key.secret bytes $key = Core\Crypto::generateKey();
// `sign` returns the token. It is valid for 15 minutes.// The token has three parts, separated by dots. This prints `3`.string $token = Core\Jwt::sign(['sub' => '42', 'name' => 'Ada'], 15m, $key);echo Core\Arr::count(Core\Str::split($token, '.')), "\n";
// `Core\Jwt::verify` checks the token with the same key and returns the claims.// This prints `42` and `Ada`.array<tainted string> $claims = Core\Jwt::verify($token, $key);echo $claims['sub'], "\n";echo $claims['name'], "\n";
// `sign` adds two claims: `iat` is the time of signing and `exp` is the expiry.// So the token has four claims. This prints `4`.echo Core\Arr::count($claims), "\n";342Ada4A key pair
<?nvs// Shows how to sign a token with a key pair, so that other services can check it.
// An `Ed25519` key pair has a private half and a public half.// The private half signs. You give the public half to the services that check.Core\Crypto\KeyPair $pair = Core\Crypto::generateKeyPair(Core\Crypto\KeyKind::Ed25519);
// 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::sign(['sub' => '42'], 1h, $pair, { kid: '2026-key' });
// The first part of the token is the header. The key chose the algorithm, `EdDSA`.// This prints `{"alg":"EdDSA","kid":"2026-key","typ":"JWT"}`.string $header = Core\Str::split($token, '.')[0];echo Core\Encoding::fromBase64Url($header) as string, "\n";{"alg":"EdDSA","kid":"2026-key","typ":"JWT"}A login cookie
<?nvs// Shows a login token: the server signs it when a user logs in, and checks it on each request.
// The server keeps one secret key. It is never sent to the browser.secret bytes $serverKey = Core\Crypto::generateKey();
// After a login, the server signs the user's id and role. The token expires after 8 hours.// The server sends the token to the browser in a cookie.string $cookie = Core\Jwt::sign(['sub' => '1042', 'role' => 'editor'], 8h, $serverKey);
// This method runs on each request. It checks if the user may edit a page.// A token that is not valid throws a `RuntimeError`, so the answer is `false`.class Login{ public static function canEdit(string $cookie, secret bytes $serverKey): bool { try { array<tainted string> $claims = Core\Jwt::verify($cookie, $serverKey); return $claims['role'] == 'editor'; } catch (RuntimeError $invalid) { return false; } }}
// The cookie the server signed. This prints `yes`.echo Login::canEdit($cookie, $serverKey) ? 'yes' : 'no', "\n";
// A user changes one character of the cookie. The signature no longer matches.// This prints `no`.echo Login::canEdit($cookie . 'x', $serverKey) ? 'yes' : 'no', "\n";yesno