Passkey Credential Store
Wisej.NET 4.2.0+
The Passkey component keeps the passkeys it registers in an IPasskeyCredentialStore. Wisej.NET has no account database of its own, so you implement this interface over your application's storage and register it with Application.Services. The component resolves it at the start of every operation and fails with PasskeyError.StoreUnavailable, before the user sees a prompt, when none is registered.
The store is a thin adapter over durable storage, but the component relies on what it promises: atomic inserts, exact comparisons, and a compare-and-update that detects concurrent changes. This page explains each of those promises, then gives a complete implementation over SQL Server you can adapt.
For a complete list of members, see the API documentation.
Is there a built-in store?
No. The framework ships no implementation of IPasskeyCredentialStore, not even an in-memory one. A store that keeps credentials in memory loses every passkey when the application restarts, while the passkeys stay on the users' devices and no longer work, and it is not shared between servers behind a load balancer. Use durable storage, also for staging; an in-memory store is only suitable for automated tests.
The contract
Scope by relying party
Every method takes, or receives on its argument, the normalized relying party id: a lower-case ASCII domain with no scheme, port or path, such as example.com. Answer only for rows with that id. A credential id or a user handle that is meaningful under one relying party is never resolved under another, even when one database serves several hosts.
Compare exactly
- Credential ids and user handles are compared by value, byte for byte.
- User ids are compared ordinally: case, accents and white space all count.
The component leaves the ownership check of a rename or a delete to the store's own comparison of the user id. Under a case-insensitive comparison, an account whose id differs from another's only in case, alice and Alice, could rename or delete the other's passkeys. In SQL, declare every user id column with a binary collation.
SQL Server's default collations are case-insensitive: use a _BIN2 collation on user id columns. MySQL's default _ci collations are case-insensitive as well: use a binary collation such as utf8mb4_bin. SQL Server also ignores trailing spaces when it compares strings, under every collation; the component refuses user ids that begin or end with white space for that reason. It also ignores trailing zero bytes when it compares binary values, which is why the sample below adds a length check to every credential id comparison.
One shared, thread-safe instance
Register the store as a ServiceLifetime.Shared service, the default, or through your own IServiceProvider as a singleton. One instance serves every session and every request at the same time, so it must be thread-safe. A store with no mutable state of its own, opening a pooled connection per call like the sample below, is thread-safe by construction. Do not register it per session: credential data never lives in a Wisej service scope, and a per-session instance holds nothing a sign-in can use.
Outcomes are return values, failures are exceptions
A missing row is a return value, false, null or PasskeyCommitResult.NotFound, never an exception. An exception thrown by any method means the store itself failed: the component reports it as PasskeyError.StoreFailed with the exception attached, and commits nothing.
Keep credential ids, user handles and key material out of those exceptions' messages. The component removes the base64 renderings it recognizes before an exception leaves it, but any other rendering, such as the hexadecimal 0x… SQL Server writes into a duplicate-key or truncation message, reaches your handlers and logs as the store wrote it.
Never return null, never mutate after returning
Methods that return arrays return an empty array, never null. GetOrCreateUserHandleAsync never returns null or an empty array. Records and arrays you return are snapshots: the component validates and deep-copies them before use and never exposes your instances. Do not rely on later changes to an object you returned or were passed; persistence happens inside the method call.
Cancellation
Every method takes a CancellationToken last, observes it where its storage can, and may throw OperationCanceledException when it is canceled. The component treats that as cancellation, not as a store failure. Translate a database driver's own cancellation error into OperationCanceledException, or the component reports it as StoreFailed.
AddCredentialAsync is the one exception to "observe it where you can": see below.
Members
| Method | Called | Must guarantee |
|---|---|---|
GetOrCreateUserHandleAsync(relyingPartyId, userId, newUserHandle, cancellationToken) | At the start of every registration. | Return the account's stored user handle, storing newUserHandle first when it has none. Atomic: two concurrent calls for one account return the same handle, and an account never ends up with two. Never null or empty. |
GetCredentialsAsync(relyingPartyId, userId, cancellationToken) | At registration (to exclude existing passkeys), on a sign-in for a named account, and by Passkey.GetCredentialsAsync. | Every credential of the account, in any order; an empty array when none. |
FindCredentialAsync(relyingPartyId, credentialId, cancellationToken) | On every sign-in, to find the credential the authenticator used. | The credential with that id, whichever account owns it, or null. |
AddCredentialAsync(credential, cancellationToken) | At the end of a verified registration. | A unique insert, never an upsert. True when inserted; false when a row with the same relying party id and credential id exists, in which case nothing is written. |
CommitAuthenticationAsync(update, cancellationToken) | After a sign-in is verified and Authenticating has passed. | An atomic compare-and-update; see below. |
RenameCredentialAsync(relyingPartyId, userId, credentialId, name, cancellationToken) | By Passkey.RenameCredentialAsync. | Change only Name of the row with that relying party, credential id and owner; false when there is none, including when another account owns it. Rotate the concurrency token. |
DeleteCredentialAsync(relyingPartyId, userId, credentialId, cancellationToken) | By Passkey.DeleteCredentialAsync. | Remove the row with that relying party, credential id and owner; false when there is none, including when another account owns it. |
GetOrCreateUserHandleAsync
newUserHandle is 64 random bytes the component generated. Store it only when the account has no handle yet, and return whatever handle the account has afterwards. The store never derives a handle from the user id, a name or an e-mail address. The handle is stable for the life of the account and shared by every credential of that account under one relying party, so it belongs to the account (one row per relying party and user id), not to a credential.
FindCredentialAsync
Sign-in without a user name needs this lookup: the account is not known until the row is found. A sign-in for a named account uses it too, then checks PasskeyCredential.UserId against the account named. Return exactly the credential asked for; a record with another credential id is a contract breach the component reports as PasskeyError.Configuration.
AddCredentialAsync
Insert the record with every member the component set. If a row with the same relying party id and credential id exists, write nothing and return false; the component reports PasskeyError.CredentialExists. Two concurrent inserts of the same id must leave exactly one row, which a unique constraint gives you.
Observe the cancellation token only until the row is durable. Once the insert has committed, return true rather than throw: the component treats true as the end of the registration, which then completes even if it was canceled while this call was in flight. Throwing after the commit leaves a passkey in the store and on the device that the application was told failed. The sample checks the token before the insert and then executes it without the token.
CommitAuthenticationAsync
After a verified sign-in, the component moves the credential to its new state with a PasskeyAuthenticationUpdate:
| Property | Use |
|---|---|
RelyingPartyId, CredentialId | The row to update. |
ExpectedSignCount | The counter the row had when the sign-in read it. |
ExpectedConcurrencyToken | The concurrency token the row had when the sign-in read it; an empty array, never null, when it had none. |
SignCount, BackedUp, LastUsedAt | The new values. |
UserVerified | Whether this sign-in verified the user with a credential whose verification is established. |
Update the row only if it still has the expected counter and, for a store that issues tokens, the expected token. Comparison and write are one atomic operation, so two sign-ins that cross commit in some order and the second one sees a conflict. Return:
PasskeyCommitResult.Updatedwhen the row matched and the new values were written. Only then does the component sign the user in.PasskeyCommitResult.Conflictwhen the row exists but no longer matches. The sign-in fails withPasskeyError.StoreConflictand the user simply tries again.PasskeyCommitResult.NotFoundwhen the row no longer exists. Never recreate it.
The write changes exactly four values: SignCount, BackedUp, LastUsedAt, and UserVerified, which becomes its stored value OR update.UserVerified, so it is never cleared. Rotate the concurrency token when you use one. Never touch the key, the algorithm, the account, the user handle, the name, the creation time or the registration evidence.
Concurrency tokens
PasskeyCredential.ConcurrencyToken is an opaque value your store uses to detect that a row changed: a row version, a timestamp, random bytes. The component reads it with the record and hands it back byte for byte as ExpectedConcurrencyToken; it never interprets it. You may assign it on insert.
A store can rely on SignCount alone and leave the token null, but it then cannot tell a credential that was deleted and registered again under the same id from the original while a sign-in is in flight, because a re-inserted row may carry the same counter. A row deleted and inserted again is not the row the sign-in read, and must commit as Conflict or NotFound, never as Updated.
A store that issues tokens therefore:
- gives every inserted row a token no earlier row with that id ever carried: a SQL Server
ROWVERSION, or fresh random bytes. A per-row version number that restarts at 1 on insert does not qualify; - gives a token to every row, including rows written before it started using tokens;
- compares a null token and an empty one as the same missing token;
- rotates the token on every change, including a rename, so a sign-in that read the row before the rename commits as
Conflictinstead of overwriting the name.
RenameCredentialAsync and DeleteCredentialAsync
Both carry the owner's user id. Match the row on relying party id, credential id and user id, compared ordinally. This comparison is the only ownership check there is: Passkey.RenameCredentialAsync and Passkey.DeleteCredentialAsync make none of their own.
name has already been validated and trimmed by the component; null clears the name. A delete is final: a sign-in in flight against the removed row commits as NotFound and fails. Removing the row does not remove the passkey from the user's device or password manager; the application tells the user so.
What to persist
PasskeyCredential is both the record your store keeps and what the component hands to your application. The component fills every member at registration; your store materializes the same members from its rows.
| Member | Type | Notes |
|---|---|---|
RelyingPartyId | string | Lower-case ASCII domain, at most 253 characters. Part of the key. Required. |
CredentialId | byte[] | 1 to 1023 bytes, unique per relying party. Part of the key. Required. |
UserId | string | Your account id, at most 256 characters. Compared ordinally. Required. |
UserHandle | byte[] | The account's 64-byte handle. Compared exactly with what the authenticator returns. Required. |
PublicKey | byte[] | COSE key; about 77 bytes for ES256, up to about 2 KB for RS256. Required. |
Algorithm | int | -7 (ES256) or -257 (RS256). Required. |
SignCount | uint | Store the full unsigned 32-bit range; in SQL Server a BIGINT. Required. |
ConcurrencyToken | byte[] | Yours; see above. |
Name | string | At most 256 characters, or null. Display only. |
CreatedAt | DateTimeOffset | UTC. Required. |
LastUsedAt | DateTimeOffset? | UTC, null until first used. |
Transports | string[] | At most 8 entries of lower-case letters, digits and hyphens, at most 32 characters each; an empty array when none. Browser-supplied text: encode it on output. |
Discoverable | bool? | Null when the browser did not say. |
Aaguid | Guid | The authenticator model; Guid.Empty is normal. Advisory, not verified. |
UserVerified | bool | Whether user verification was established at registration. Only ever goes from false to true through a commit. Required. |
BackupEligible | bool | Set at registration and never changed; a sign-in whose flag differs fails. Required. |
BackedUp | bool | Whether the passkey is currently synced. Required. |
AttestationObject | byte[] | Registration evidence, up to 8 KB, or null for an imported record. |
ClientDataJson | byte[] | Registration evidence, up to 8 KB, or null for an imported record. |
Evidence | PasskeyCredentialEvidence | NativeVerified for every record this version writes; ImportedLegacy is reserved for imported records. |
The evidence members, AttestationObject, ClientDataJson and Evidence, are kept exactly as received so that a later attestation policy or a verifier fix can re-examine a registration. Persist them, even though nothing reads them during sign-in.
After registration, PublicKey, Algorithm, AttestationObject, ClientDataJson, Aaguid, Transports, Discoverable, BackupEligible, CreatedAt and Evidence never change; SignCount, BackedUp, LastUsedAt and UserVerified change only through CommitAuthenticationAsync; Name only through RenameCredentialAsync.
The public key is not secret. The credential id, the user handle and the raw registration evidence are privacy-sensitive identifiers: do not log or serialize records wholesale.
Registering the store
Register a single shared instance before the first page uses a Passkey component, for example in the static Program constructor. Read the connection string from configuration, never from a file in the web root:
static Program()
{
var connectionString = ConfigurationManager.ConnectionStrings["Passkeys"].ConnectionString;
Application.Services.AddService<IPasskeyCredentialStore>(
new SqlPasskeyCredentialStore(connectionString));
}
On .NET, read it from the host's configuration in Startup instead:
var builder = WebApplication.CreateBuilder(args);
Application.Services.AddService<IPasskeyCredentialStore>(
new SqlPasskeyCredentialStore(builder.Configuration.GetConnectionString("Passkeys")));
If you have replaced Wisej.NET's provider with Microsoft's IServiceProvider, register it there as a singleton instead, with builder.Services.AddSingleton<IPasskeyCredentialStore>(...). See Dependency Injection.
Sample: SQL Server
The sample below is a complete, durable store over SQL Server 2016 or later, or Azure SQL Database, in plain ADO.NET with the Microsoft.Data.SqlClient package. It compiles against .NET Framework 4.8 and .NET, and needs nothing from your application but a connection string. Adapt the schema name, the table names and the error handling to your conventions; keep the constraints and the comparisons.
Tables
-- One row per account and relying party: the account's WebAuthn user handle.
CREATE TABLE dbo.PasskeyUsers
(
RelyingPartyId VARCHAR(253) COLLATE Latin1_General_100_BIN2 NOT NULL,
UserId NVARCHAR(256) COLLATE Latin1_General_100_BIN2 NOT NULL,
UserHandle VARBINARY(64) NOT NULL,
CONSTRAINT PK_PasskeyUsers PRIMARY KEY (RelyingPartyId, UserId),
CONSTRAINT UQ_PasskeyUsers_UserHandle UNIQUE (RelyingPartyId, UserHandle),
CONSTRAINT CK_PasskeyUsers_UserHandle CHECK (DATALENGTH(UserHandle) BETWEEN 1 AND 64)
);
-- One row per registered passkey.
CREATE TABLE dbo.PasskeyCredentials
(
Id BIGINT IDENTITY(1, 1) NOT NULL,
RelyingPartyId VARCHAR(253) COLLATE Latin1_General_100_BIN2 NOT NULL,
CredentialId VARBINARY(1023) NOT NULL,
UserId NVARCHAR(256) COLLATE Latin1_General_100_BIN2 NOT NULL,
UserHandle VARBINARY(64) NOT NULL,
PublicKey VARBINARY(4096) NOT NULL,
Algorithm INT NOT NULL,
SignCount BIGINT NOT NULL,
ConcurrencyToken ROWVERSION NOT NULL,
Name NVARCHAR(256) NULL,
CreatedAt DATETIMEOFFSET(7) NOT NULL,
LastUsedAt DATETIMEOFFSET(7) NULL,
Transports VARCHAR(300) NOT NULL,
Discoverable BIT NULL,
Aaguid UNIQUEIDENTIFIER NOT NULL,
UserVerified BIT NOT NULL,
BackupEligible BIT NOT NULL,
BackedUp BIT NOT NULL,
AttestationObject VARBINARY(MAX) NULL,
ClientDataJson VARBINARY(MAX) NULL,
Evidence TINYINT NOT NULL,
CONSTRAINT PK_PasskeyCredentials PRIMARY KEY CLUSTERED (Id),
-- A credential id is unique per relying party: this is what makes the insert a unique insert.
CONSTRAINT UQ_PasskeyCredentials_CredentialId UNIQUE NONCLUSTERED (RelyingPartyId, CredentialId),
CONSTRAINT FK_PasskeyCredentials_PasskeyUsers FOREIGN KEY (RelyingPartyId, UserId)
REFERENCES dbo.PasskeyUsers (RelyingPartyId, UserId),
CONSTRAINT CK_PasskeyCredentials_CredentialId CHECK (DATALENGTH(CredentialId) BETWEEN 1 AND 1023),
CONSTRAINT CK_PasskeyCredentials_Algorithm CHECK (Algorithm IN (-7, -257)),
CONSTRAINT CK_PasskeyCredentials_SignCount CHECK (SignCount BETWEEN 0 AND 4294967295),
CONSTRAINT CK_PasskeyCredentials_Evidence CHECK (Evidence IN (0, 1))
);
CREATE NONCLUSTERED INDEX IX_PasskeyCredentials_User
ON dbo.PasskeyCredentials (RelyingPartyId, UserId);
Why it looks the way it does:
_BIN2collations onUserIdmake every comparison ordinal, as the contract requires. The relying party id is ASCII and already lower-case, so a binary collation costs nothing there either.- The unique constraint on (
RelyingPartyId,CredentialId) turns two concurrent inserts of one credential into one row and one duplicate-key error, which the store reports as false. It is nonclustered with a surrogate clustered key because a 1023-byte credential id exceeds the 900-byte limit of a clustered key; nonclustered keys allow 1700 bytes from SQL Server 2016 on. ROWVERSIONis the concurrency token. SQL Server changes it on every update, rename included, and a re-inserted row always gets a value no earlier row had, which is exactly whatCommitAuthenticationAsyncneeds.SignCountis aBIGINTwith a check constraint, because the counter is an unsigned 32-bit value that does not fit anINT.VARBINARY(MAX)holds the registration evidence, which can reach 8 KB, more thanVARBINARY(8000)allows.- The foreign key keeps every credential attached to an account that has a user handle. When you delete an account, delete its rows from
PasskeyCredentialsfirst, then fromPasskeyUsers.
The store
using System;
using System.Collections.Generic;
using System.Data;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Data.SqlClient;
using Wisej.Web;
namespace MyApp.Security
{
/// <summary>
/// Application code: an IPasskeyCredentialStore over SQL Server.
/// Stateless apart from the connection string, so one instance serves every session.
/// </summary>
public sealed class SqlPasskeyCredentialStore : IPasskeyCredentialStore
{
// SQL Server ignores trailing 0x00 bytes when it compares binary values, so every
// credential id comparison also compares lengths.
private const string MatchCredential =
"RelyingPartyId = @RelyingPartyId AND CredentialId = @CredentialId " +
"AND DATALENGTH(CredentialId) = DATALENGTH(@CredentialId)";
private const string SelectColumns =
"SELECT RelyingPartyId, CredentialId, UserId, UserHandle, PublicKey, Algorithm, " +
"SignCount, ConcurrencyToken, Name, CreatedAt, LastUsedAt, Transports, Discoverable, " +
"Aaguid, UserVerified, BackupEligible, BackedUp, AttestationObject, ClientDataJson, Evidence " +
"FROM dbo.PasskeyCredentials ";
private readonly string connectionString;
public SqlPasskeyCredentialStore(string connectionString)
{
if (string.IsNullOrEmpty(connectionString))
throw new ArgumentNullException(nameof(connectionString));
this.connectionString = connectionString;
}
public async Task<byte[]> GetOrCreateUserHandleAsync(
string relyingPartyId, string userId, byte[] newUserHandle, CancellationToken cancellationToken)
{
// UPDLOCK + HOLDLOCK serialize concurrent calls for the same account: the first
// inserts, every other one waits and then reads the handle the first one stored.
const string sql =
"SET NOCOUNT ON; SET XACT_ABORT ON; " +
"BEGIN TRANSACTION; " +
"INSERT INTO dbo.PasskeyUsers (RelyingPartyId, UserId, UserHandle) " +
"SELECT @RelyingPartyId, @UserId, @UserHandle " +
"WHERE NOT EXISTS (SELECT 1 FROM dbo.PasskeyUsers WITH (UPDLOCK, HOLDLOCK) " +
"WHERE RelyingPartyId = @RelyingPartyId AND UserId = @UserId); " +
"COMMIT TRANSACTION; " +
"SELECT UserHandle FROM dbo.PasskeyUsers " +
"WHERE RelyingPartyId = @RelyingPartyId AND UserId = @UserId;";
try
{
using (var connection = await OpenAsync(cancellationToken).ConfigureAwait(false))
using (var command = new SqlCommand(sql, connection))
{
AddRelyingPartyId(command, relyingPartyId);
AddUserId(command, userId);
command.Parameters.Add("@UserHandle", SqlDbType.VarBinary, 64).Value = newUserHandle;
var handle = await command.ExecuteScalarAsync(cancellationToken).ConfigureAwait(false) as byte[];
if (handle == null || handle.Length == 0)
throw new InvalidOperationException("The passkey store holds no user handle for the account.");
return handle;
}
}
catch (SqlException ex)
{
throw StoreFailure(ex, cancellationToken);
}
}
public async Task<PasskeyCredential[]> GetCredentialsAsync(
string relyingPartyId, string userId, CancellationToken cancellationToken)
{
const string sql = SelectColumns + "WHERE RelyingPartyId = @RelyingPartyId AND UserId = @UserId;";
try
{
using (var connection = await OpenAsync(cancellationToken).ConfigureAwait(false))
using (var command = new SqlCommand(sql, connection))
{
AddRelyingPartyId(command, relyingPartyId);
AddUserId(command, userId);
var credentials = new List<PasskeyCredential>();
using (var reader = await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false))
{
while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
credentials.Add(ReadCredential(reader));
}
return credentials.ToArray();
}
}
catch (SqlException ex)
{
throw StoreFailure(ex, cancellationToken);
}
}
public async Task<PasskeyCredential> FindCredentialAsync(
string relyingPartyId, byte[] credentialId, CancellationToken cancellationToken)
{
const string sql = SelectColumns + "WHERE " + MatchCredential + ";";
try
{
using (var connection = await OpenAsync(cancellationToken).ConfigureAwait(false))
using (var command = new SqlCommand(sql, connection))
{
AddRelyingPartyId(command, relyingPartyId);
AddCredentialId(command, credentialId);
using (var reader = await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false))
{
if (await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
return ReadCredential(reader);
return null;
}
}
}
catch (SqlException ex)
{
throw StoreFailure(ex, cancellationToken);
}
}
public async Task<bool> AddCredentialAsync(PasskeyCredential credential, CancellationToken cancellationToken)
{
if (credential == null)
throw new ArgumentNullException(nameof(credential));
// ConcurrencyToken is not inserted: SQL Server assigns the ROWVERSION.
const string sql =
"INSERT INTO dbo.PasskeyCredentials (RelyingPartyId, CredentialId, UserId, UserHandle, " +
"PublicKey, Algorithm, SignCount, Name, CreatedAt, LastUsedAt, Transports, Discoverable, " +
"Aaguid, UserVerified, BackupEligible, BackedUp, AttestationObject, ClientDataJson, Evidence) " +
"VALUES (@RelyingPartyId, @CredentialId, @UserId, @UserHandle, " +
"@PublicKey, @Algorithm, @SignCount, @Name, @CreatedAt, @LastUsedAt, @Transports, @Discoverable, " +
"@Aaguid, @UserVerified, @BackupEligible, @BackedUp, @AttestationObject, @ClientDataJson, @Evidence);";
try
{
using (var connection = await OpenAsync(cancellationToken).ConfigureAwait(false))
using (var command = new SqlCommand(sql, connection))
{
AddRelyingPartyId(command, credential.RelyingPartyId);
AddCredentialId(command, credential.CredentialId);
AddUserId(command, credential.UserId);
command.Parameters.Add("@UserHandle", SqlDbType.VarBinary, 64).Value = credential.UserHandle;
command.Parameters.Add("@PublicKey", SqlDbType.VarBinary, 4096).Value = credential.PublicKey;
command.Parameters.Add("@Algorithm", SqlDbType.Int).Value = credential.Algorithm;
command.Parameters.Add("@SignCount", SqlDbType.BigInt).Value = (long)credential.SignCount;
command.Parameters.Add("@Name", SqlDbType.NVarChar, 256).Value = (object)credential.Name ?? DBNull.Value;
command.Parameters.Add("@CreatedAt", SqlDbType.DateTimeOffset).Value = credential.CreatedAt;
command.Parameters.Add("@LastUsedAt", SqlDbType.DateTimeOffset).Value = (object)credential.LastUsedAt ?? DBNull.Value;
command.Parameters.Add("@Transports", SqlDbType.VarChar, 300).Value =
credential.Transports == null ? string.Empty : string.Join(" ", credential.Transports);
command.Parameters.Add("@Discoverable", SqlDbType.Bit).Value = (object)credential.Discoverable ?? DBNull.Value;
command.Parameters.Add("@Aaguid", SqlDbType.UniqueIdentifier).Value = credential.Aaguid;
command.Parameters.Add("@UserVerified", SqlDbType.Bit).Value = credential.UserVerified;
command.Parameters.Add("@BackupEligible", SqlDbType.Bit).Value = credential.BackupEligible;
command.Parameters.Add("@BackedUp", SqlDbType.Bit).Value = credential.BackedUp;
command.Parameters.Add("@AttestationObject", SqlDbType.VarBinary, -1).Value = (object)credential.AttestationObject ?? DBNull.Value;
command.Parameters.Add("@ClientDataJson", SqlDbType.VarBinary, -1).Value = (object)credential.ClientDataJson ?? DBNull.Value;
command.Parameters.Add("@Evidence", SqlDbType.TinyInt).Value = (byte)credential.Evidence;
// Observe cancellation only until the row is durable: once the INSERT runs,
// it is not canceled, and a committed insert returns true.
cancellationToken.ThrowIfCancellationRequested();
await command.ExecuteNonQueryAsync(CancellationToken.None).ConfigureAwait(false);
return true;
}
}
catch (SqlException ex) when (ex.Number == 2627 || ex.Number == 2601)
{
// Unique constraint violation: the credential id is already registered for this
// relying party. Nothing was written, and the existing row is untouched.
return false;
}
catch (SqlException ex)
{
throw StoreFailure(ex, CancellationToken.None);
}
}
public async Task<PasskeyCommitResult> CommitAuthenticationAsync(
PasskeyAuthenticationUpdate update, CancellationToken cancellationToken)
{
if (update == null)
throw new ArgumentNullException(nameof(update));
// Compare and write in one statement; the ROWVERSION rotates by itself.
// 0 = Updated, 1 = Conflict (the row exists but changed), 2 = NotFound.
const string sql =
"SET NOCOUNT ON; " +
"UPDATE dbo.PasskeyCredentials SET " +
"SignCount = @SignCount, BackedUp = @BackedUp, LastUsedAt = @LastUsedAt, " +
"UserVerified = CASE WHEN @UserVerified = 1 THEN 1 ELSE UserVerified END " +
"WHERE " + MatchCredential + " " +
"AND SignCount = @ExpectedSignCount AND ConcurrencyToken = @ExpectedConcurrencyToken; " +
"IF @@ROWCOUNT = 1 SELECT 0; " +
"ELSE IF EXISTS (SELECT 1 FROM dbo.PasskeyCredentials WHERE " + MatchCredential + ") SELECT 1; " +
"ELSE SELECT 2;";
try
{
using (var connection = await OpenAsync(cancellationToken).ConfigureAwait(false))
using (var command = new SqlCommand(sql, connection))
{
AddRelyingPartyId(command, update.RelyingPartyId);
AddCredentialId(command, update.CredentialId);
command.Parameters.Add("@SignCount", SqlDbType.BigInt).Value = (long)update.SignCount;
command.Parameters.Add("@BackedUp", SqlDbType.Bit).Value = update.BackedUp;
command.Parameters.Add("@LastUsedAt", SqlDbType.DateTimeOffset).Value = update.LastUsedAt;
command.Parameters.Add("@UserVerified", SqlDbType.Bit).Value = update.UserVerified;
command.Parameters.Add("@ExpectedSignCount", SqlDbType.BigInt).Value = (long)update.ExpectedSignCount;
command.Parameters.Add("@ExpectedConcurrencyToken", SqlDbType.VarBinary, 8).Value =
update.ExpectedConcurrencyToken ?? new byte[0];
var outcome = (int)await command.ExecuteScalarAsync(cancellationToken).ConfigureAwait(false);
switch (outcome)
{
case 0: return PasskeyCommitResult.Updated;
case 1: return PasskeyCommitResult.Conflict;
default: return PasskeyCommitResult.NotFound;
}
}
}
catch (SqlException ex)
{
throw StoreFailure(ex, cancellationToken);
}
}
public async Task<bool> RenameCredentialAsync(
string relyingPartyId, string userId, byte[] credentialId, string name, CancellationToken cancellationToken)
{
// The owner is part of the match: another account's credential is "not found".
const string sql =
"UPDATE dbo.PasskeyCredentials SET Name = @Name " +
"WHERE " + MatchCredential + " AND UserId = @UserId;";
try
{
using (var connection = await OpenAsync(cancellationToken).ConfigureAwait(false))
using (var command = new SqlCommand(sql, connection))
{
AddRelyingPartyId(command, relyingPartyId);
AddCredentialId(command, credentialId);
AddUserId(command, userId);
command.Parameters.Add("@Name", SqlDbType.NVarChar, 256).Value = (object)name ?? DBNull.Value;
return await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false) == 1;
}
}
catch (SqlException ex)
{
throw StoreFailure(ex, cancellationToken);
}
}
public async Task<bool> DeleteCredentialAsync(
string relyingPartyId, string userId, byte[] credentialId, CancellationToken cancellationToken)
{
const string sql =
"DELETE FROM dbo.PasskeyCredentials " +
"WHERE " + MatchCredential + " AND UserId = @UserId;";
try
{
using (var connection = await OpenAsync(cancellationToken).ConfigureAwait(false))
using (var command = new SqlCommand(sql, connection))
{
AddRelyingPartyId(command, relyingPartyId);
AddCredentialId(command, credentialId);
AddUserId(command, userId);
return await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false) == 1;
}
}
catch (SqlException ex)
{
throw StoreFailure(ex, cancellationToken);
}
}
private async Task<SqlConnection> OpenAsync(CancellationToken cancellationToken)
{
var connection = new SqlConnection(this.connectionString);
try
{
await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
return connection;
}
catch
{
connection.Dispose();
throw;
}
}
private static void AddRelyingPartyId(SqlCommand command, string relyingPartyId)
{
// VarChar to match the column type, so the index is used without a conversion.
command.Parameters.Add("@RelyingPartyId", SqlDbType.VarChar, 253).Value = relyingPartyId;
}
private static void AddUserId(SqlCommand command, string userId)
{
command.Parameters.Add("@UserId", SqlDbType.NVarChar, 256).Value = userId;
}
private static void AddCredentialId(SqlCommand command, byte[] credentialId)
{
command.Parameters.Add("@CredentialId", SqlDbType.VarBinary, 1023).Value = credentialId;
}
private static PasskeyCredential ReadCredential(SqlDataReader reader)
{
var transports = reader.GetString(11);
return new PasskeyCredential
{
RelyingPartyId = reader.GetString(0),
CredentialId = reader.GetFieldValue<byte[]>(1),
UserId = reader.GetString(2),
UserHandle = reader.GetFieldValue<byte[]>(3),
PublicKey = reader.GetFieldValue<byte[]>(4),
Algorithm = reader.GetInt32(5),
SignCount = checked((uint)reader.GetInt64(6)),
ConcurrencyToken = reader.GetFieldValue<byte[]>(7),
Name = reader.IsDBNull(8) ? null : reader.GetString(8),
CreatedAt = reader.GetDateTimeOffset(9),
LastUsedAt = reader.IsDBNull(10) ? (DateTimeOffset?)null : reader.GetDateTimeOffset(10),
Transports = transports.Length == 0
? new string[0]
: transports.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries),
Discoverable = reader.IsDBNull(12) ? (bool?)null : reader.GetBoolean(12),
Aaguid = reader.GetGuid(13),
UserVerified = reader.GetBoolean(14),
BackupEligible = reader.GetBoolean(15),
BackedUp = reader.GetBoolean(16),
AttestationObject = reader.IsDBNull(17) ? null : reader.GetFieldValue<byte[]>(17),
ClientDataJson = reader.IsDBNull(18) ? null : reader.GetFieldValue<byte[]>(18),
Evidence = (PasskeyCredentialEvidence)reader.GetByte(19)
};
}
private static Exception StoreFailure(SqlException exception, CancellationToken cancellationToken)
{
// A command canceled through the token surfaces as a SqlException: report it as the
// cancellation it is, which the component does not count as a store failure.
if (cancellationToken.IsCancellationRequested)
return new OperationCanceledException(cancellationToken);
// The SqlException is deliberately not attached: SQL Server writes binary values as
// 0x... hexadecimal in some messages (duplicate keys, truncation), which the component
// does not scrub. The error number is enough to look the failure up.
return new InvalidOperationException(
"The passkey store failed with SQL Server error " + exception.Number + ".");
}
}
}
Notes on the sample:
- Every member of the interface is implemented with its exact signature. No method returns null except
FindCredentialAsyncfor a missing credential, as the contract allows. - Outcomes are return values. A duplicate insert returns false, a rename or delete of a row that does not exist, or belongs to another account, returns false, and a commit reports
ConflictorNotFound. Only a database failure throws. - The commit is one statement. The
UPDATEcompares the counter and theROWVERSIONand writes in one operation, so two crossing sign-ins cannot both succeed, and a credential deleted in between is never recreated. - Transports are stored space-separated. The component keeps only entries of lower-case letters, digits and hyphens, so a space never occurs inside one.
- Deleting accounts. The interface has no method for removing an account, because the component never does. Your account deletion removes the account's rows from
PasskeyCredentialsandPasskeyUsersitself.
Other databases
The same design works on any database that offers a unique constraint, an atomic conditional update, and exact comparisons:
- Key the credentials table on (relying party id, credential id) with a unique constraint, and the user handle table on (relying party id, user id).
- Compare user ids with a case-sensitive, accent-sensitive, binary or ordinal collation.
- Implement the commit as one conditional
UPDATEand inspect the affected row count, then check whether the row still exists to tellConflictfromNotFound. - Use a token no earlier row ever carried, such as a database-wide row version or 16 fresh random bytes written on every insert and every update.
- Return false for a duplicate insert by catching the database's own unique-violation error, never by checking first and inserting second, which two concurrent registrations can both pass.
An ORM such as Entity Framework works too, as long as it is used with a context per call (the store instance is shared by every session), the unique index and the binary collation exist in the database, and the commit is a conditional update rather than a read followed by a save.