Core\Passkey::verifyRegistration
Core\Passkey::verifyRegistration(
string $response,
string $rpId,
string $origin,
): Core\Passkey\CredentialChecks the browser's answer to the options from Core\Passkey::registerOptions, and returns the new passkey as a Core\Passkey\Credential.
In the browser, navigator.credentials.create() creates the passkey. Send JSON.stringify(credential.toJSON()) to the server, and pass that text as $response. Pass the same domain as for registerOptions, and the address of your site, such as https://example.com.
Save the four values of the passkey with the account: id(), publicKey(), algorithm() and signCount(). You need them when the user signs in.
Good to know: the check deletes the challenge from the session first. So a second check of the same answer throws a RuntimeError. A check after a failed check also throws one.
The examples below show a new passkey, the same answer checked twice, and both halves of a page that saves a passkey.
Parameters
$responsestringThe credential thatnavigator.credentials.create()returned, as JSON. In the browser,JSON.stringify(credential)makes it.$rpIdstringThe same domain that you passed toregisterOptions.$originstringThe address of your site in the browser, such ashttps://example.com. The answer must name exactly this origin.
Return value
Returns Core\Passkey\Credential. The new passkey, with its id, its public key, its algorithm and its sign counter.
Errors
LogicErrorThe program is not handling a request. A command-line program, a job and a test have no session.RuntimeErrorThe session store, where the server keeps session data, cannot be opened. This happens only at the first call in the request that uses the session. With the default store, the cause is that the server has no data folder. With[session] backend = "shared",[cache.shared] urlis not set, or the program does not have thecache.sharedcapability.IOErrorThe store cannot be reached. The user may still have a session there, so do not treat them as signed out.RuntimeErrorNo registration is waiting, or the challenge is older than five minutes. It is also thrown when a check fails. The checks are the challenge, the origin, the domain, the user verification and the key algorithm. An answer longer than 64 KB also throws.
Changelog
| Version | Change |
|---|---|
0.0.5 | Core\Csrf::token and the Core\Passkey methods that save or check a challenge open the session on their first use. You do not call anything before them. In a program that handles no request, they throw a LogicError. |
Examples
The examples below run with this configuration file.
# The challenge is saved in the session, and a session keeps its data in a store.# These examples use the Redis server on this computer at port 16379,# and allow the program to use it.[capabilities.cache]shared = true
[session]backend = "shared"
[cache.shared]url = "redis://127.0.0.1:16379"A new passkey
<?nvs// Shows how a server checks the browser's answer and reads the new passkey.// requires: redis
// This class plays the browser and the device. In real use, the browser makes this answer.// It follows the WebAuthn standard, and you do not write this code yourself.final class Device{ public static function answer(string $options, string $origin): tainted string { var $read = Core\Json::decode($options) as array<mixed>; tainted string $client = '{"type":"webauthn.create","challenge":"' . ($read['challenge'] as string) . '","origin":"' . $origin . '"}'; bytes $id = Core\Random::bytes(16); var $key = Core\Crypto::generateKeyPair(Core\Crypto\KeyKind::Ed25519); bytes $data = Core\Bytes::join([ Core\Hash::of('example.com', Core\Hash::Digest::Sha256), Core\Encoding::fromHex('450000000000000000000000000000000000000000'), Core\Bytes::pack('n', 16), $id, Core\Encoding::fromHex('a4010103272006215820'), $key->publicKey()->write(Core\Crypto\PublicKey::Format::Raw), ]); bytes $object = Core\Bytes::join([ Core\Encoding::fromHex('a363666d74646e6f6e656761747453746d74a068617574684461746158'), Core\Bytes::pack('C', Core\Bytes::length($data)), $data, ]); string $raw = Core\Encoding::toBase64Url($id); return '{"type":"public-key","id":"' . $raw . '","rawId":"' . $raw . '","response":{"clientDataJSON":"' . Core\Encoding::toBase64Url(Core\Encoding::encodeText($client, Core\Charset::Utf8)) . '","attestationObject":"' . Core\Encoding::toBase64Url($object) . '"}}'; }}
// The server makes the options. The challenge in them is saved in the session.string $options = Core\Passkey::registerOptions('example.com', 'Example Shop', Core\Random::bytes(16), 'ada@example.com');
// The browser sends its answer. Text from a request is `tainted`.tainted string $answer = Device::answer($options, 'https://example.com');
// The server checks the answer for its own domain and address.Core\Passkey\Credential $passkey = Core\Passkey::verifyRegistration($answer, 'example.com', 'https://example.com');
// Save these four values with the account. You need them when the user signs in.echo 'id: ', Core\Bytes::length($passkey->id()), " bytes\n";echo 'public key: ', Core\Bytes::length($passkey->publicKey()), " bytes\n";echo 'algorithm: ', $passkey->algorithm() == Core\Passkey\Credential::Algorithm::Ed25519 ? 'Ed25519' : 'ES256', "\n";echo 'sign counter: ', $passkey->signCount(), "\n";id: 16 bytespublic key: 42 bytesalgorithm: Ed25519sign counter: 0The same answer twice
<?nvs// Shows that an answer can be checked only once. A second check of the same answer throws an error.// requires: redis
// This class plays the browser and the device. In real use, the browser makes this answer.// It follows the WebAuthn standard, and you do not write this code yourself.final class Device{ public static function answer(string $options, string $origin): tainted string { var $read = Core\Json::decode($options) as array<mixed>; tainted string $client = '{"type":"webauthn.create","challenge":"' . ($read['challenge'] as string) . '","origin":"' . $origin . '"}'; bytes $id = Core\Random::bytes(16); var $key = Core\Crypto::generateKeyPair(Core\Crypto\KeyKind::Ed25519); bytes $data = Core\Bytes::join([ Core\Hash::of('example.com', Core\Hash::Digest::Sha256), Core\Encoding::fromHex('450000000000000000000000000000000000000000'), Core\Bytes::pack('n', 16), $id, Core\Encoding::fromHex('a4010103272006215820'), $key->publicKey()->write(Core\Crypto\PublicKey::Format::Raw), ]); bytes $object = Core\Bytes::join([ Core\Encoding::fromHex('a363666d74646e6f6e656761747453746d74a068617574684461746158'), Core\Bytes::pack('C', Core\Bytes::length($data)), $data, ]); string $raw = Core\Encoding::toBase64Url($id); return '{"type":"public-key","id":"' . $raw . '","rawId":"' . $raw . '","response":{"clientDataJSON":"' . Core\Encoding::toBase64Url(Core\Encoding::encodeText($client, Core\Charset::Utf8)) . '","attestationObject":"' . Core\Encoding::toBase64Url($object) . '"}}'; }}
string $options = Core\Passkey::registerOptions('example.com', 'Example Shop', Core\Random::bytes(16), 'ada@example.com');tainted string $answer = Device::answer($options, 'https://example.com');
// The first check succeeds. It also deletes the challenge from the session.Core\Passkey::verifyRegistration($answer, 'example.com', 'https://example.com');echo "first check: the passkey is new\n";
// The second check of the same answer throws a `RuntimeError`.// Somebody who copied the answer cannot use it to add a passkey.try { Core\Passkey::verifyRegistration($answer, 'example.com', 'https://example.com'); echo "second check: the passkey is new\n";} catch (RuntimeError $e) { echo 'second check: ', $e->message, "\n";}first check: the passkey is newsecond check: Core\Passkey::verifyRegistration(): no challenge is waiting in this session. Each challenge can be checked only once, so call the options method again.A page that saves a passkey
<?nvs// Shows the browser half and the server half of a page that saves a new passkey with an account.// requires: redis
// This class plays the browser and the device. In real use, the browser makes this answer.// It follows the WebAuthn standard, and you do not write this code yourself.final class Device{ public static function answer(string $options, string $origin): tainted string { var $read = Core\Json::decode($options) as array<mixed>; tainted string $client = '{"type":"webauthn.create","challenge":"' . ($read['challenge'] as string) . '","origin":"' . $origin . '"}'; bytes $id = Core\Random::bytes(16); var $key = Core\Crypto::generateKeyPair(Core\Crypto\KeyKind::Ed25519); bytes $data = Core\Bytes::join([ Core\Hash::of('example.com', Core\Hash::Digest::Sha256), Core\Encoding::fromHex('450000000000000000000000000000000000000000'), Core\Bytes::pack('n', 16), $id, Core\Encoding::fromHex('a4010103272006215820'), $key->publicKey()->write(Core\Crypto\PublicKey::Format::Raw), ]); bytes $object = Core\Bytes::join([ Core\Encoding::fromHex('a363666d74646e6f6e656761747453746d74a068617574684461746158'), Core\Bytes::pack('C', Core\Bytes::length($data)), $data, ]); string $raw = Core\Encoding::toBase64Url($id); return '{"type":"public-key","id":"' . $raw . '","rawId":"' . $raw . '","response":{"clientDataJSON":"' . Core\Encoding::toBase64Url(Core\Encoding::encodeText($client, Core\Charset::Utf8)) . '","attestationObject":"' . Core\Encoding::toBase64Url($object) . '"}}'; }}
class Account{ // A real application saves the passkeys in its database. public array<Core\Passkey\Credential> $passkeys = [];
public function constructor(public bytes $id, public string $email) {}}
class PasskeyPage{ // The browser half. This JavaScript creates the passkey and sends the answer to the server. public static function script(): string { return "const response = await fetch('/account/passkey/options', { method: 'POST' });\n" . "const options = PublicKeyCredential.parseCreationOptionsFromJSON(await response.json());\n" . "const passkey = await navigator.credentials.create({ publicKey: options });\n" . "await fetch('/account/passkey', { method: 'POST', body: JSON.stringify(passkey.toJSON()) });\n"; }
// The server half for the first `fetch`. It returns the options. public static function options(Account $account): string { return Core\Passkey::registerOptions('example.com', 'Example Shop', $account->id, $account->email, $account->passkeys); }
// The server half for the second `fetch`. It checks the answer and saves the four values. public static function save(Account $account, tainted string $body): void { Core\Passkey\Credential $passkey = Core\Passkey::verifyRegistration($body, 'example.com', 'https://example.com'); $account->passkeys[] = Core\Passkey\Credential::of( $passkey->id(), $passkey->publicKey(), $passkey->algorithm(), $passkey->signCount(), ); }}
// The page contains this script.echo PasskeyPage::script(), "\n";
// The script asks for the options, and the device answers them.Account $ada = new Account(Core\Random::bytes(16), 'ada@example.com');string $options = PasskeyPage::options($ada);tainted string $body = Device::answer($options, 'https://example.com');
// The script sends the answer, and the server saves the passkey. This prints `1`.PasskeyPage::save($ada, $body);echo 'passkeys of ', $ada->email, ': ', Core\Arr::count($ada->passkeys), "\n";const response = await fetch('/account/passkey/options', { method: 'POST' });const options = PublicKeyCredential.parseCreationOptionsFromJSON(await response.json());const passkey = await navigator.credentials.create({ publicKey: options });await fetch('/account/passkey', { method: 'POST', body: JSON.stringify(passkey.toJSON()) });
passkeys of ada@example.com: 1