Core\Passkey::verifySignIn
Core\Passkey::verifySignIn(
string $response,
Core\Passkey\Credential $stored,
string $rpId,
string $origin,
): Core\Passkey\CredentialChecks the browser's answer to the options from Core\Passkey::signInOptions against a saved passkey. It returns the passkey as a Core\Passkey\Credential with its new sign counter.
In the browser, navigator.credentials.get() signs the challenge. Send JSON.stringify(credential.toJSON()) to the server, and pass that text as $response. Use Core\Passkey::credentialId to find the saved passkey, and pass it as $stored. Pass the same domain as for signInOptions, and the address of your site, such as https://example.com.
The method checks the signature with the saved public key. It also checks the challenge, the domain and the address. If one check fails, it throws a RuntimeError.
Save the result again. The device counts its sign-ins. The new counter must be higher than the saved one, or the method throws. A counter that does not rise can mean a copied passkey. Some devices always send 0. When both counters are 0, the sign-in succeeds.
Good to know: the check deletes the challenge from the session first. So a second check of the same answer throws a RuntimeError.
The examples below show one sign-in, the same answer checked twice, and both halves of a sign-in page.
Parameters
$responsestringThe credential thatnavigator.credentials.get()returned, as JSON.$storedCore\Passkey\CredentialThe saved passkey with the id thatcredentialIdreturned.$rpIdstringThe same domain that you passed tosignInOptions.$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 passkey with its new 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 sign-in is waiting, or the challenge is older than five minutes. It is also thrown when a check fails. The checks are the passkey id, the challenge, the origin, the domain, the user verification, the signature and the sign counter. 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"Sign in with a passkey
<?nvs// Shows how a server checks a sign-in with a saved passkey and reads the new sign counter.// 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 signIn(string $options, Core\Crypto\KeyPair $key, bytes $id, int $count): tainted string { var $read = Core\Json::decode($options) as array<mixed>; string $challenge = Core\Taint::assertTrusted($read['challenge'] as string, 'this program wrote the options'); bytes $client = Core\Encoding::encodeText( '{"type":"webauthn.get","challenge":"' . $challenge . '","origin":"https://example.com"}', Core\Charset::Utf8, ); bytes $data = Core\Bytes::join([ Core\Hash::of('example.com', Core\Hash::Digest::Sha256), Core\Bytes::pack('C', 0x05), Core\Bytes::pack('N', $count), ]); bytes $signature = Core\Crypto::sign(Core\Bytes::join([$data, Core\Hash::of($client, Core\Hash::Digest::Sha256)]), $key); return '{"type":"public-key","id":"' . Core\Encoding::toBase64Url($id) . '","response":{"clientDataJSON":"' . Core\Encoding::toBase64Url($client) . '","authenticatorData":"' . Core\Encoding::toBase64Url($data) . '","signature":"' . Core\Encoding::toBase64Url($signature) . '"}}'; }}
// The application saved this passkey when the user registered it. Its sign counter is 4.Core\Crypto\KeyPair $key = Core\Crypto::generateKeyPair(Core\Crypto\KeyKind::Ed25519);bytes $publicKey = Core\Bytes::join([ Core\Encoding::fromHex('a4010103272006215820'), $key->publicKey()->write(Core\Crypto\PublicKey::Format::Raw),]);Core\Passkey\Credential $saved = Core\Passkey\Credential::of( Core\Random::bytes(16), $publicKey, Core\Passkey\Credential::Algorithm::Ed25519, 4,);
// The server makes the options. The challenge in them is saved in the session.string $options = Core\Passkey::signInOptions('example.com', [$saved]);
// The device signs the challenge. Its counter is now 5.tainted string $answer = Device::signIn($options, $key, $saved->id(), 5);
// The server checks the signature with the saved passkey. The result has the new counter.Core\Passkey\Credential $now = Core\Passkey::verifySignIn($answer, $saved, 'example.com', 'https://example.com');echo 'signed in: ', $now->id() == $saved->id() ? 'yes' : 'no', "\n";echo 'saved counter: ', $saved->signCount(), "\n";echo 'new counter: ', $now->signCount(), "\n";signed in: yessaved counter: 4new counter: 5The same answer twice
<?nvs// Shows that a sign-in 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 signIn(string $options, Core\Crypto\KeyPair $key, bytes $id, int $count): tainted string { var $read = Core\Json::decode($options) as array<mixed>; string $challenge = Core\Taint::assertTrusted($read['challenge'] as string, 'this program wrote the options'); bytes $client = Core\Encoding::encodeText( '{"type":"webauthn.get","challenge":"' . $challenge . '","origin":"https://example.com"}', Core\Charset::Utf8, ); bytes $data = Core\Bytes::join([ Core\Hash::of('example.com', Core\Hash::Digest::Sha256), Core\Bytes::pack('C', 0x05), Core\Bytes::pack('N', $count), ]); bytes $signature = Core\Crypto::sign(Core\Bytes::join([$data, Core\Hash::of($client, Core\Hash::Digest::Sha256)]), $key); return '{"type":"public-key","id":"' . Core\Encoding::toBase64Url($id) . '","response":{"clientDataJSON":"' . Core\Encoding::toBase64Url($client) . '","authenticatorData":"' . Core\Encoding::toBase64Url($data) . '","signature":"' . Core\Encoding::toBase64Url($signature) . '"}}'; }}
// The application saved this passkey when the user registered it.Core\Crypto\KeyPair $key = Core\Crypto::generateKeyPair(Core\Crypto\KeyKind::Ed25519);bytes $publicKey = Core\Bytes::join([ Core\Encoding::fromHex('a4010103272006215820'), $key->publicKey()->write(Core\Crypto\PublicKey::Format::Raw),]);Core\Passkey\Credential $saved = Core\Passkey\Credential::of( Core\Random::bytes(16), $publicKey, Core\Passkey\Credential::Algorithm::Ed25519, 0,);
string $options = Core\Passkey::signInOptions('example.com', [$saved]);tainted string $answer = Device::signIn($options, $key, $saved->id(), 1);
// The first check succeeds. It also deletes the challenge from the session.$saved = Core\Passkey::verifySignIn($answer, $saved, 'example.com', 'https://example.com');echo 'first check: signed in, counter ', $saved->signCount(), "\n";
// The second check of the same answer throws a `RuntimeError`.// Somebody who copied the answer cannot use it to sign in.try { Core\Passkey::verifySignIn($answer, $saved, 'example.com', 'https://example.com'); echo "second check: signed in\n";} catch (RuntimeError $e) { echo 'second check: ', $e->message, "\n";}first check: signed in, counter 1second check: Core\Passkey::verifySignIn(): no challenge is waiting in this session. Each challenge can be checked only once, so call the options method again.A sign in page
<?nvs// Shows the browser half and the server half of a page that signs in with a 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 signIn(string $options, Core\Crypto\KeyPair $key, bytes $id, int $count): tainted string { var $read = Core\Json::decode($options) as array<mixed>; string $challenge = Core\Taint::assertTrusted($read['challenge'] as string, 'this program wrote the options'); bytes $client = Core\Encoding::encodeText( '{"type":"webauthn.get","challenge":"' . $challenge . '","origin":"https://example.com"}', Core\Charset::Utf8, ); bytes $data = Core\Bytes::join([ Core\Hash::of('example.com', Core\Hash::Digest::Sha256), Core\Bytes::pack('C', 0x05), Core\Bytes::pack('N', $count), ]); bytes $signature = Core\Crypto::sign(Core\Bytes::join([$data, Core\Hash::of($client, Core\Hash::Digest::Sha256)]), $key); return '{"type":"public-key","id":"' . Core\Encoding::toBase64Url($id) . '","response":{"clientDataJSON":"' . Core\Encoding::toBase64Url($client) . '","authenticatorData":"' . Core\Encoding::toBase64Url($data) . '","signature":"' . Core\Encoding::toBase64Url($signature) . '"}}'; }}
class Account{ // A real application saves the passkey in its database. public function constructor(public string $email, public Core\Passkey\Credential $passkey) {}}
class SignInPage{ // The browser half. This JavaScript gets the options, signs in with a passkey and sends the answer. public static function script(): string { return "const response = await fetch('/sign-in/options', { method: 'POST' });\n" . "const options = PublicKeyCredential.parseRequestOptionsFromJSON(await response.json());\n" . "const credential = await navigator.credentials.get({ publicKey: options });\n" . "await fetch('/sign-in', { method: 'POST', body: JSON.stringify(credential.toJSON()) });\n"; }
// The server half for the first `fetch`. It returns the options. public static function options(): string { return Core\Passkey::signInOptions('example.com'); }
// The server half for the second `fetch`. It finds the account by the passkey id and checks the answer. // Then it saves the passkey with its new counter. It returns the account, or `null`. public static function signIn(tainted string $body, array<Account> $accounts): ?Account { var $id = Core\Passkey::credentialId($body); foreach ($accounts as Account $account) { if ($account->passkey->id() == $id) { $account->passkey = Core\Passkey::verifySignIn($body, $account->passkey, 'example.com', 'https://example.com'); return $account; } } return null; }}
// The page contains this script.echo SignInPage::script(), "\n";
// The application saved a passkey for each account. Here the keys are made with `Core\Crypto`.array<Account> $accounts = [];array<Core\Crypto\KeyPair> $keys = [];array<string> $emails = ['ada@example.com', 'grace@example.com'];foreach ($emails as string $email) { Core\Crypto\KeyPair $key = Core\Crypto::generateKeyPair(Core\Crypto\KeyKind::Ed25519); bytes $publicKey = Core\Bytes::join([ Core\Encoding::fromHex('a4010103272006215820'), $key->publicKey()->write(Core\Crypto\PublicKey::Format::Raw), ]); var $passkey = Core\Passkey\Credential::of(Core\Random::bytes(16), $publicKey, Core\Passkey\Credential::Algorithm::Ed25519, 7); $accounts[] = new Account($email, $passkey); $keys[] = $key;}
// The script asks for the options, and Grace's device signs them with its counter at 8.string $options = SignInPage::options();tainted string $body = Device::signIn($options, $keys[1], $accounts[1]->passkey->id(), 8);
// The script sends the answer. The server signs Grace in and saves the counter `8`.?Account $account = SignInPage::signIn($body, $accounts);echo $account == null ? 'unknown passkey' : 'signed in: ' . $account->email, "\n";echo 'saved counter: ', $accounts[1]->passkey->signCount(), "\n";const response = await fetch('/sign-in/options', { method: 'POST' });const options = PublicKeyCredential.parseRequestOptionsFromJSON(await response.json());const credential = await navigator.credentials.get({ publicKey: options });await fetch('/sign-in', { method: 'POST', body: JSON.stringify(credential.toJSON()) });
signed in: grace@example.comsaved counter: 8