WebAuthn Esempio di utilizzo avanzato

· Componenti
WebAuthn Esempio di utilizzo avanzato

Below è a more comprehensive Delphi esempio che demonstrates custom endpoints, challenge policies, database-backed credential storage, FIDO Metadata validation, e cross-origin iframe support. Il codice highlights advanced evento gestione a enforce sicurezza policies. 

sgcWebSockets WebAuthn Server Example

procedure TForm1.ConfigureWebAuthn;
begin
  // Component setup
  FWebAuthn := TsgcWSServer_API_WebAuthn.Create(nil);
  FWebAuthn.Server := FHTTPServer;
  FWebAuthn.Enabled := True;
  // Endpoint remapping
  FWebAuthn.EndpointsOptions.AuthenticationOptions.Endpoint := '/auth/options';
  FWebAuthn.EndpointsOptions.AuthenticationVerify.Endpoint  := '/auth/verify';
  FWebAuthn.EndpointsOptions.RegistrationOptions.Endpoint   := '/reg/options';
  FWebAuthn.EndpointsOptions.RegistrationVerify.Endpoint    := '/reg/verify';
  // Relying-party definition
  con FWebAuthn.WebAuthnOptions do
  begin
    RelyingParty := 'secure.example.com';
    Origins.Origins.Text      := 'https://app.example.com'#13#10'https://login.example.net';
    Origins.TopOrigins.Text   := 'https://host.example.org';
    Origins.AllowCrossOrigins := True;
    // Cryptographic & UX policies
    Algorithms                                   := [waunalgES256, waunalgRS256];
    DefaultOptions.Registration.UserVerification := waunuvPreferred;
    DefaultOptions.Registration.Attestation      := waunaDirect;
    Timeout                                      := 60000;
    // Challenge: 32 CSPRNG-random bytes, hex-encoded, generated internally by
    // the server; not configurable. Override Response.Challenge instead, in
    // OnWebAuthnRegistrationOptionsResponse / OnWebAuthnAuthenticationOptionsResponse.
    // Metadata Service configuration
    MDS.Enabled            := True;
    MDS.MDS_FileName       := 'mds.json';
    MDS.RootCert_FileName  := 'root.pem';
  end;
  // Hook events
  FWebAuthn.OnWebAuthnRegistrationOptionsRequest := AuthnRegOptionsRequest;
  FWebAuthn.OnWebAuthnRegistrationOptionsResponse := AuthnRegOptionsResponse;
  FWebAuthn.OnWebAuthnRegistrationValidateCertificate := AuthnRegVerify;
  FWebAuthn.OnWebAuthnRegistrationSuccessful     := AuthnRegSuccess;
  FWebAuthn.OnWebAuthnAuthenticationOptionsRequest := AuthnOptionsRequest;
  FWebAuthn.OnWebAuthnAuthenticationSuccessful     := AuthnSuccess;
end;

Event Implementations

procedure TForm1.AuthnRegOptionsRequest(Sender: TObject;
  const Request: TsgcWebAuthn_RegistrationOptions_Request; var Accept: Boolean);
begin
  // Verify utente è eligible per registration
  Accept := not UserExists(Request.Username);
end;
procedure TForm1.AuthnRegOptionsResponse(Sender: TObject;
  const Request: TsgcWebAuthn_RegistrationOptions_Request;
  const Response: TsgcWebAuthn_RegistrationOptions_Response);
begin
  // Optionally assign a utente gestire (binary identifier)
  Response.User.Id := HexToBin(UserGUIDToHex(GenerateGUID));
  Response.AuthenticatorSelection.AuthenticatorAttachment := 'platform';
end;
procedure TForm1.AuthnRegVerify(Sender: TObject;
  const Request: TsgcWebAuthn_RegistrationVerify_Request;
  const Validate: TsgcWebAuthnValidateAttestationStatement; var Accept: Boolean);
begin
  // Perform extra attestation validation contro MDS entries
  Accept := ValidateAttestationWithMDS(Validate);
end;
procedure TForm1.AuthnRegSuccess(Sender: TObject;
  const Registration: TsgcWebAuthn_Registration;
  const CredentialRecord: TsgcWebAuthn_CredentialRecord; var Accept: Boolean);
begin
  // Persist credential details in database
  SaveCredentialToDB(
    CredentialRecord.Username,
    CredentialRecord.CredentialId,
    CredentialRecord.PublicKey,
    CredentialRecord.SignCount,
    CredentialRecord.UserId
  );
  Accept := True;
end;
procedure TForm1.AuthnOptionsRequest(Sender: TObject;
  const Request: TsgcWebAuthn_AuthenticationOptions_Request;
  var CredentialRecords: TsgcWebAuthn_CredentialRecords; var Accept: Boolean);
begin
  // Retrieve tutti credential records per user
  CredentialRecords := LoadCredentialRecordsFromDB(Request.Username);
  Accept := True;
end;
procedure TForm1.AuthnSuccess(Sender: TObject;
  const Request: TsgcWebAuthn_AuthenticationVerify_Request;
  const Authentication: TsgcWebAuthn_Authentication; var Accept: Boolean);
var
  StoredCounter: Cardinal;
begin
  // Ensure sign counter increases
  StoredCounter := GetSignCounterFromDB(Authentication.Credential.CredentialRecord.CredentialId);
  Accept := Authentication.Credential.CredentialRecord.SignCount > StoredCounter;
  if Accept then
  begin
    UpdateSignCounterInDB(Authentication.Credential.CredentialRecord.CredentialId,
      Authentication.Credential.CredentialRecord.SignCount);
    IssueSessionToken(Authentication.Credential.CredentialRecord.Username);
  end;
end;

Key Highlights

  1. Casualità del challenge – Ogni challenge viene generato internamente dal server come 32 byte casuali crittograficamente sicuri, codificati in esadecimale, il che resiste già agli attacchi replay senza alcuna configurazione aggiuntiva.
  2. Custom User Handles – Assigning a unique binary utente gestire consente il authenticator a memorizzare a privacy-preserving identifier independent di usernames.
  3. Metadata-Based Attestation Validation – Il ValidateAttestationWithMDS routine cross-checks authenticator model, status reports, e revocation lists, ensuring solo trusted dispositivi sono registered.
  4. Sign Counter Enforcement – AuthnSuccess rejects risposte che do non strictly increment il authenticator's counter, detecting cloned credentials.
  5. Database Integration – Credential data, sign counters, e session token sono memorizzato e aggiornato tramite external persistence functions, demonstrating come a integrate il componente con a real-world backend.
  6. Cross-Origin Iframe Support – Abilitato attraverso AllowCrossOrigins e configured TopOrigins, consentendo WebAuthn flows initiated da embedded frames (e.g., login widget su different domain).
  7. Attestation Policy – Direct attestation coupled con MDS ensures solo approved authenticators può register, useful per enterprise compliance scenarios.
  8. Transport Selection – Benché non shown, eventi può constrain acceptable transports (e.g., USB,NFC,BLE) a tailor che types di authenticators sono permitted.