Core\Passkey::signInOptions
Core\Passkey::signInOptions(
string $rpId,
array<Core\Passkey\Credential> $allowed = [],
): stringReturns the options a browser needs to sign in with a passkey, as a JSON string.
Send the JSON to the page. There, JavaScript passes it to PublicKeyCredential.parseRequestOptionsFromJSON(), and the result to navigator.credentials.get(). The browser asks the user to choose a passkey and gives back its answer. Read the passkey id in that answer with Core\Passkey::credentialId, and check the answer with Core\Passkey::verifySignIn.
The options contain a new random challenge, which is saved in the session. If the visitor has no session yet, the call creates one. A challenge can be checked once, and only for five minutes. A new call replaces the challenge of the last call. The options also ask the device to check that the user is really there, with a fingerprint, a face or a PIN.
Good to know: when you know the account, pass its passkeys as $allowed. The browser then offers only those. When $allowed is empty, the browser shows every passkey it has for your site.
The examples below show the options for any passkey, the options for the passkeys of one account, and both halves of a sign-in page.
Parameters
$rpIdstringThe domain of your site, such asexample.com. Use the same domain as forregisterOptions.$allowedarray<Core\Passkey\Credential>default []The passkeys of the account that signs in. Leave it empty when you do not know the account yet. The browser then shows every passkey it has for your site.
Return value
Returns string. A JSON string. In the browser, pass it to PublicKeyCredential.parseRequestOptionsFromJSON(), and pass the result to navigator.credentials.get().
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.LogicErrorThe call is insideCore\Html::laterorCore\Task::runAfterResponse. The response headers are already sent there, so the challenge cannot be saved in the session.LogicError$rpIdis empty.
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"The options for any passkey
<?nvs// Shows the options a server sends to the browser to sign in with a passkey.// requires: redis
// The account is not known yet, so no passkeys are passed. `signInOptions` saves// the challenge in the session, and the session opens on this first use.string $json = Core\Passkey::signInOptions('example.com');
// The challenge is random, so this prints only the fields that are the same each time.var $options = Core\Json::decode($json) as array<mixed>;echo 'site: ', $options['rpId'] as string, "\n";echo 'user verification: ', $options['userVerification'] as string, "\n";
// `timeout` is in milliseconds. This prints `300000`, which is five minutes.echo 'timeout: ', $options['timeout'] as int, "\n";
// The list of allowed passkeys is empty. The browser shows every passkey it has for the site.echo 'allowed passkeys: ', Core\Arr::count($options['allowCredentials'] as array<mixed>), "\n";
// The challenge is 32 random bytes, written as 43 characters.echo 'challenge: ', Core\Str::length($options['challenge'] as string), " characters\n";site: example.comuser verification: requiredtimeout: 300000allowed passkeys: 0challenge: 43 charactersThe passkeys of one account
<?nvs// Shows how the passkeys of one account go into the options to sign in.// requires: redis
// The account has a passkey on a laptop and one on a phone. The application stored them.// Here they are made up: an Ed25519 public key from `Core\Crypto`, and random ids.var $key = Core\Crypto::generateKeyPair(Core\Crypto\KeyKind::Ed25519);bytes $raw = $key->publicKey()->write(Core\Crypto\PublicKey::Format::Raw);bytes $publicKey = Core\Bytes::join([Core\Encoding::fromHex('a4010103272006215820'), $raw]);array<Core\Passkey\Credential> $passkeys = [ Core\Passkey\Credential::of(Core\Random::bytes(16), $publicKey, Core\Passkey\Credential::Algorithm::Ed25519, 0), Core\Passkey\Credential::of(Core\Random::bytes(16), $publicKey, Core\Passkey\Credential::Algorithm::Ed25519, 0),];
// `$allowed` lists the passkeys the browser may use. Other passkeys are not offered.string $json = Core\Passkey::signInOptions('example.com', $passkeys);
// The options list both passkeys under `allowCredentials`. This prints `2`.var $options = Core\Json::decode($json) as array<mixed>;var $allowed = $options['allowCredentials'] as array<mixed>;echo 'allowed passkeys: ', Core\Arr::count($allowed), "\n";
// Each id in the options is the stored id, written in base64url.var $second = $allowed[1] as array<mixed>;bool $same = ($second['id'] as string) == Core\Encoding::toBase64Url($passkeys[1]->id());echo 'the second one is the phone: ', $same ? 'yes' : 'no', "\n";allowed passkeys: 2the second one is the phone: yesA sign in page
<?nvs// Shows the browser half and the server half of a sign-in page that gets its options.// requires: redis
class SignInPage{ // The browser half. This JavaScript gets the options from the server, // lets the user sign in with a passkey and sends the answer back to the server. 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. It answers the first `fetch` in the script. public static function options(): string { return Core\Passkey::signInOptions('example.com'); }}
// The page contains this script.echo SignInPage::script(), "\n";
// This request is the script's first `fetch`. The challenge is new for every request,// so this prints only the site.var $options = Core\Json::decode(SignInPage::options()) as array<mixed>;echo 'options for ', $options['rpId'] as string, "\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()) });
options for example.com