WebAuthn Advanced Usage Example

· 컴포넌트

Below is a more comprehensive Delphi example that demonstrates custom endpoints, challenge policies, database-backed credential storage, FIDO Metadata validation, and cross-origin iframe support. The code highlights advanced event handling to enforce security policies. 

sgcWebSockets WebAuthn 서버 예제

procedure TForm1.ConfigureWebAuthn;
begin
  // Component setup
  FWebAuthn := TsgcWSAPIServer_WebAuthn.Create(nil);
  FWebAuthn.Server := FHTTPServer;
  FWebAuthn.Enabled := True;
  // Endpoint remapping
  FWebAuthn.EndpointOptions.AuthenticationOptions := '/auth/options';
  FWebAuthn.EndpointOptions.AuthenticationVerify  := '/auth/verify';
  FWebAuthn.EndpointOptions.RegistrationOptions   := '/reg/options';
  FWebAuthn.EndpointOptions.RegistrationVerify    := '/reg/verify';
  // Relying-party definition
  with FWebAuthn.WebAuthnOptions do
  begin
    RelyingParty := 'secure.example.com';
    Origins      := 'https://app.example.com;https://login.example.net';
    TopOrigins   := 'https://host.example.org';
    AllowCrossOrigins := True;
    // Cryptographic & UX policies
    Algorithms       := 'ES256,RS256';
    UserVerification := 'preferred';
    Attestation      := 'direct';
    TimeoutMS        := 60000;
    // Challenge settings
    ChallengeOptions.ChallengeSize := 64; // 512-bit challenges
    ChallengeOptions.RandomFunc    := MyCryptoRandom; // custom RNG
    // Metadata Service configuration
    MDS.Enabled            := True;
    MDS.MDS_FileName       := 'mds.json';
    MDS.RootCert_FileName  := 'root.pem';
  end;
  // Hook events
  FWebAuthn.OnWebAuthnRegistrationOptionsRequest := AuthnRegOptionsRequest;
  FWebAuthn.OnWebAuthnRegistrationVerify         := AuthnRegVerify;
  FWebAuthn.OnWebAuthnRegistrationSuccessful     := AuthnRegSuccess;
  FWebAuthn.OnWebAuthnAuthenticationOptionsRequest := AuthnOptionsRequest;
  FWebAuthn.OnWebAuthnAuthenticationVerify         := AuthnVerify;
  FWebAuthn.OnWebAuthnAuthenticationSuccessful     := AuthnSuccess;
end;

이벤트 구현

procedure TForm1.AuthnRegOptionsRequest(Sender: TObject;
  const Request: TsgcWebAuthnRequestOptions; Response: TsgcWebAuthnResponseOptions);
begin
  // Verify user is eligible for registration
  if UserExists(Request.Username) then
    raise Exception.Create('Username already registered');
  // Optionally assign a user handle (binary identifier)
  Response.User.ID := HexToBin(UserGUIDToHex(GenerateGUID));
  Response.AuthenticatorSelection.AuthenticatorAttachment := 'platform';
end;
procedure TForm1.AuthnRegVerify(Sender: TObject; const Credential: TsgcWebAuthnCredential; var Success: Boolean);
begin
  // Perform extra attestation validation against MDS entries
  Success := ValidateAttestationWithMDS(Credential);
end;
procedure TForm1.AuthnRegSuccess(Sender: TObject; const Credential: TsgcWebAuthnCredential);
begin
  // Persist credential details in database
  SaveCredentialToDB(
    Credential.Username,
    Credential.CredentialID,
    Credential.PublicKey,
    Credential.SignCount,
    Credential.UserHandle
  );
end;
procedure TForm1.AuthnOptionsRequest(Sender: TObject;
  const Request: TsgcWebAuthnRequestOptions; Response: TsgcWebAuthnResponseOptions);
begin
  // Retrieve all credential IDs for user
  Response.AllowCredentials := LoadCredentialIdsFromDB(Request.Username);
end;
procedure TForm1.AuthnVerify(Sender: TObject; const Credential: TsgcWebAuthnCredential; var Success: Boolean);
var
  StoredCounter: Cardinal;
begin
  // Ensure sign counter increases
  StoredCounter := GetSignCounterFromDB(Credential.CredentialID);
  if Credential.SignCount <= StoredCounter then
    Success := False
  else
    Success := True;
end;
procedure TForm1.AuthnSuccess(Sender: TObject; const Credential: TsgcWebAuthnCredential);
begin
  UpdateSignCounterInDB(Credential.CredentialID, Credential.SignCount);
  IssueSessionToken(Credential.Username);
end;

주요 특징

  1. 챌린지 강화 – 챌린지 크기를 늘리고 암호학적으로 안전한 RNG를 사용해 재생 공격을 더욱 완화해요.
  2. 커스텀 사용자 핸들 – 고유한 바이너리 사용자 핸들을 지정하면 인증자가 사용자 이름과 독립된 개인 정보 보호 식별자를 저장할 수 있어요.
  3. 메타데이터 기반 증명 검증ValidateAttestationWithMDS 루틴은 인증자 모델, 상태 보고서, 해지 목록을 교차 확인해 신뢰할 수 있는 디바이스만 등록되도록 해요.
  4. 서명 카운터 적용AuthnVerify는 인증자의 카운터를 엄격하게 증가시키지 않는 응답을 거부해 복제된 자격 증명을 감지해요.
  5. 데이터베이스 통합 – 자격 증명 데이터, 서명 카운터, 세션 토큰이 외부 지속성 함수를 통해 저장 및 업데이트되어 실제 백엔드와 컴포넌트를 통합하는 방법을 보여줘요.
  6. 교차 출처 iframe 지원AllowCrossOrigins와 설정된 TopOrigins를 통해 활성화되며, 내장 프레임에서 시작된 WebAuthn 흐름(예: 다른 도메인의 로그인 위젯)을 허용해요.
  7. 증명 정책 – MDS와 결합된 직접 증명은 승인된 인증자만 등록할 수 있도록 해 엔터프라이즈 규정 준수 시나리오에 유용해요.
  8. 전송 선택 – 표시되지 않았지만 이벤트는 허용 가능한 전송(예: USB,NFC,BLE)을 제한해 허용되는 인증자 유형을 조정할 수 있어요.