Request Options Schemas - FeitianTech/postquantum-webauthn-platform GitHub Wiki
Request Options Schemas
Table of Contents
- Introduction
- Core Schema Classes
- PublicKeyCredentialCreationOptions Schema
- PublicKeyCredentialRequestOptions Schema
- Data Types and Field Specifications
- JSON Serialization and Base64URL Encoding
- Feature Flags and Configuration
- Server Route Implementation
- Frontend Integration
- Examples and Usage Patterns
- Troubleshooting Guide
Introduction
The Post-Quantum WebAuthn Platform implements comprehensive request options schemas for both registration (creation) and authentication (assertion) flows. These schemas define the structure and validation rules for WebAuthn credential creation and verification requests, ensuring secure and standardized communication between clients and servers.
The platform supports both classical and post-quantum cryptographic algorithms, with sophisticated handling of binary data through base64url encoding and flexible JSON serialization mechanisms.
Core Schema Classes
The WebAuthn request options are implemented as Python data classes that inherit from _WebAuthnDataObject, providing robust type checking, validation, and serialization capabilities.
classDiagram
class _WebAuthnDataObject {
+__getitem__(key) Any
+from_dict(data) Self
+_parse_value(t, value) Any
}
class PublicKeyCredentialCreationOptions {
+rp : PublicKeyCredentialRpEntity
+user : PublicKeyCredentialUserEntity
+challenge : bytes
+pub_key_cred_params : Sequence[PublicKeyCredentialParameters]
+timeout : Optional[int]
+exclude_credentials : Optional[Sequence[PublicKeyCredentialDescriptor]]
+authenticator_selection : Optional[AuthenticatorSelectionCriteria]
+attestation : Optional[AttestationConveyancePreference]
+extensions : Optional[Mapping[str, Any]]
}
class PublicKeyCredentialRequestOptions {
+challenge : bytes
+timeout : Optional[int]
+rp_id : Optional[str]
+allow_credentials : Optional[Sequence[PublicKeyCredentialDescriptor]]
+user_verification : Optional[UserVerificationRequirement]
+extensions : Optional[Mapping[str, Any]]
}
class _JsonDataObject {
+__getitem__(key) Any
+_parse_value(t, value) Any
}
_WebAuthnDataObject --|> _JsonDataObject
PublicKeyCredentialCreationOptions --|> _WebAuthnDataObject
PublicKeyCredentialRequestOptions --|> _WebAuthnDataObject
Diagram sources
Section sources
PublicKeyCredentialCreationOptions Schema
The PublicKeyCredentialCreationOptions class defines the parameters for credential registration requests, enabling users to create new WebAuthn credentials.
Schema Structure
| Field | Type | Required | Description |
|---|---|---|---|
rp |
PublicKeyCredentialRpEntity |
Yes | Relying Party entity information |
user |
PublicKeyCredentialUserEntity |
Yes | User account information |
challenge |
bytes |
Yes | Cryptographic challenge for authentication |
pub_key_cred_params |
Sequence[PublicKeyCredentialParameters] |
Yes | Supported public key credential parameters |
timeout |
Optional[int] |
No | Request timeout in milliseconds |
exclude_credentials |
Optional[Sequence[PublicKeyCredentialDescriptor]] |
No | Credentials to exclude from registration |
authenticator_selection |
Optional[AuthenticatorSelectionCriteria] |
No | Authenticator selection criteria |
attestation |
Optional[AttestationConveyancePreference] |
No | Attestation conveyance preference |
extensions |
Optional[Mapping[str, Any]] |
No | Extension-specific parameters |
Field Details
rp (Relying Party Entity)
- Type:
PublicKeyCredentialRpEntity - Purpose: Identifies the service requesting credential creation
- Required Fields:
name(string),id(optional string) - Validation: Must be properly formatted with valid domain identifiers
user (User Entity)
- Type:
PublicKeyCredentialUserEntity - Purpose: Contains user identification and profile information
- Required Fields:
name(string),id(bytes) - Optional Fields:
display_name(string)
challenge (Cryptographic Challenge)
- Type:
bytes - Purpose: Random data used to prevent replay attacks
- Requirements: Must be cryptographically secure random bytes
- Encoding: Automatically base64url-encoded during JSON serialization
pub_key_cred_params (Public Key Parameters)
- Type:
Sequence[PublicKeyCredentialParameters] - Purpose: Specifies supported cryptographic algorithms
- Structure: Each element contains
typeandalgfields - Common Algorithms: ES256 (-7), RS256 (-257), ML-DSA variants (-48, -49, -50)
Section sources
PublicKeyCredentialRequestOptions Schema
The PublicKeyCredentialRequestOptions class defines the parameters for authentication requests, enabling users to verify their identity using existing WebAuthn credentials.
Schema Structure
| Field | Type | Required | Description |
|---|---|---|---|
challenge |
bytes |
Yes | Cryptographic challenge for authentication |
timeout |
Optional[int] |
No | Request timeout in milliseconds |
rp_id |
Optional[str] |
No | Expected relying party identifier |
allow_credentials |
Optional[Sequence[PublicKeyCredentialDescriptor]] |
No | Credentials allowed for authentication |
user_verification |
Optional[UserVerificationRequirement] |
No | User verification requirement |
extensions |
Optional[Mapping[str, Any]] |
No | Extension-specific parameters |
Field Details
challenge (Authentication Challenge)
- Type:
bytes - Purpose: Unique data for each authentication request
- Security: Must be unpredictable and securely generated
- Expiration: Typically valid for short duration (seconds)
rp_id (Relying Party Identifier)
- Type:
Optional[str] - Purpose: Validates the authenticator's RP context
- Validation: Must match the authenticator's registered RP ID
- Default: Inherited from server configuration if not specified
allow_credentials (Allowed Credentials)
- Type:
Optional[Sequence[PublicKeyCredentialDescriptor>] - Purpose: Restricts authentication to specific credentials
- Structure: Each descriptor contains
type,id, and optionaltransports
user_verification (User Verification Requirement)
- Type:
Optional[UserVerificationRequirement] - Values:
REQUIRED,PREFERRED,DISCOURAGED - Purpose: Controls whether user verification is mandatory
Section sources
Data Types and Field Specifications
Primitive Types
bytes (Binary Data)
- Representation: Raw binary data for cryptographic material
- Serialization: Automatically base64url-encoded to JSON strings
- Validation: Length-dependent based on cryptographic algorithm requirements
Optional Types
- Definition: Fields that may be omitted in requests
- Implementation: Uses Python
Optional[T]typing annotation - Default Behavior: Serialized as
nullin JSON when absent
Enum Types
- UserVerificationRequirement:
REQUIRED,PREFERRED,DISCOURAGED - AttestationConveyancePreference:
NONE,INDIRECT,DIRECT,ENTERPRISE - AuthenticatorAttachment:
PLATFORM,CROSS_PLATFORM - ResidentKeyRequirement:
REQUIRED,PREFERRED,DISCOURAGED
Complex Types
PublicKeyCredentialParameters
- Fields:
type(always "public-key"),alg(algorithm identifier) - Purpose: Specifies supported cryptographic algorithms
- Example Values:
-7(ES256),-257(RS256),-48(ML-DSA-44)
PublicKeyCredentialDescriptor
- Fields:
type(always "public-key"),id(credential identifier),transports(optional) - Purpose: References existing credentials for authentication
- Credential ID: Base64url-encoded binary identifier
Section sources
JSON Serialization and Base64URL Encoding
Automatic Serialization Process
The platform implements sophisticated JSON serialization that automatically handles binary data conversion:
flowchart TD
A["Python Object"] --> B["_JsonDataObject.__getitem__"]
B --> C{"Field Type?"}
C --> |bytes| D["websafe_encode()"]
C --> |Mapping| E["Convert to dict"]
C --> |Other| F["Direct Serialization"]
D --> G["Base64URL String"]
E --> H["Recursive Processing"]
F --> I["JSON String"]
G --> I
H --> I
Diagram sources
Base64URL Encoding Functions
The platform provides two core functions for binary-to-text encoding:
websafe_encode()
- Purpose: Converts binary data to URL-safe base64 string
- Implementation: Uses
urlsafe_b64encode()from Python standard library - Character Set: Uses
-and_instead of+and/ - Padding: Omits trailing
=characters
websafe_decode()
- Purpose: Converts URL-safe base64 string back to binary data
- Implementation: Handles automatic padding calculation
- Compatibility: Supports both legacy and modern base64url formats
JSON Mapping Feature
The webauthn_json_mapping feature controls serialization behavior:
| Mode | Behavior | Use Case |
|---|---|---|
Enabled (True) |
JSON-friendly serialization with base64 encoding | Modern WebAuthn implementations |
Disabled (False) |
Legacy serialization with minimal transformation | Backward compatibility |
Section sources
Feature Flags and Configuration
webauthn_json_mapping Feature
The platform supports a feature flag that affects how WebAuthn data classes handle JSON serialization:
# Enable modern JSON mapping
import fido2.features
fido2.features.webauthn_json_mapping.enabled = True
# Disable for backward compatibility
fido2.features.webauthn_json_mapping.enabled = False
Server Configuration Impact
The server configuration automatically enables appropriate features:
# Automatic feature detection and configuration
try:
fido2.features.webauthn_json_mapping.enabled = True
except Exception:
try:
fido2.features.webauthn_json.enabled = True
except Exception:
pass
Feature Detection and Compatibility
The platform maintains backward compatibility through graceful degradation:
- Modern Clients: Use JSON-friendly serialization with base64 encoding
- Legacy Clients: Fall back to traditional serialization format
- Automatic Detection: Runtime feature detection prevents breaking changes
Section sources
Server Route Implementation
Registration Endpoint (/api/register/begin)
The registration endpoint demonstrates comprehensive request option generation:
sequenceDiagram
participant Client as "Client Browser"
participant Server as "Registration Endpoint"
participant Fido2 as "Fido2 Server"
participant Session as "Session Storage"
Client->>Server : POST /api/register/begin
Server->>Server : Parse existing credentials
Server->>Fido2 : server.register_begin()
Fido2->>Fido2 : Generate challenge
Fido2->>Fido2 : Configure options
Fido2-->>Server : PublicKeyCredentialCreationOptions
Server->>Session : Store state
Server->>Server : Apply JSON mapping
Server-->>Client : JSON options with base64 encoding
Diagram sources
Authentication Endpoint (/api/authenticate/begin)
The authentication endpoint showcases request option construction for verification:
sequenceDiagram
participant Client as "Client Browser"
participant Server as "Authentication Endpoint
participant Fido2 as "Fido2 Server"
participant Storage as "Credential Storage"
Client->>Server : POST /api/authenticate/begin
Server->>Storage : Load stored credentials
Storage-->>Server : Credential descriptors
Server->>Fido2 : server.authenticate_begin()
Fido2->>Fido2 : Generate challenge
Fido2->>Fido2 : Configure allow_credentials
Fido2-->>Server : PublicKeyCredentialRequestOptions
Server->>Server : Apply JSON mapping
Server-->>Client : JSON options with base64 encoding
Diagram sources
Advanced Endpoint (/api/advanced/register/begin)
The advanced endpoint provides fine-grained control over request options:
- Custom Challenge Generation: Allows client-specified challenges
- Flexible Algorithm Selection: Supports custom algorithm lists
- Enhanced Validation: Comprehensive input validation and error handling
- Extension Support: Full support for WebAuthn extensions
Section sources
Frontend Integration
JavaScript Client Integration
The frontend implements comprehensive WebAuthn client-side handling:
// Example: Creating registration options
const registrationOptions = await navigator.credentials.create({
publicKey: {
rp: { name: "Example Service" },
user: {
id: Uint8Array.from(username, c => c.charCodeAt(0)),
name: username,
displayName: displayName
},
challenge: base64urlToUint8Array(challenge),
pubKeyCredParams: [
{ type: "public-key", alg: -7 }, // ES256
{ type: "public-key", alg: -257 } // RS256
]
}
});
Base64URL Utilities
The frontend provides essential utilities for binary data handling:
// Base64URL to Uint8Array conversion
function base64urlToUint8Array(base64url) {
let base64 = base64url.replace(/-/g, '+').replace(/_/g, '/');
while (base64.length % 4) {
base64 += '=';
}
return base64ToUint8Array(base64);
}
// Uint8Array to Base64URL conversion
function bufferToBase64url(buffer) {
const byteView = new Uint8Array(buffer);
let str = "";
for (const charCode of byteView) {
str += String.fromCharCode(charCode);
}
const base64String = btoa(str);
return base64String.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, "");
}
JSON Editor Integration
The advanced interface provides real-time JSON validation and conversion:
- Live Validation: Immediate feedback on JSON structure
- Format Conversion: Seamless switching between formats (hex, base64, base64url)
- Type Safety: Automatic type validation and coercion
- Extension Support: Dynamic extension parameter configuration
Section sources
Examples and Usage Patterns
Typical Registration Flow
Server-Side Generation
# Generate registration options
options, state = server.register_begin(
PublicKeyCredentialUserEntity(
id=b"user_id_bytes",
name="[email protected]",
display_name="User Display Name"
),
existing_credentials,
user_verification="preferred",
authenticator_attachment="cross-platform"
)
JSON Output Example
{
"publicKey": {
"rp": {
"name": "Example Service",
"id": "example.com"
},
"user": {
"name": "[email protected]",
"displayName": "User Display Name",
"id": "dXNlcm5hbWVAZXhhbXBsZS5jb20="
},
"challenge": "c29tZV9yYW5kb21fY2hhbGxlbmdl",
"pubKeyCredParams": [
{"type": "public-key", "alg": -7},
{"type": "public-key", "alg": -257}
],
"timeout": 60000,
"attestation": "direct"
}
}
Typical Authentication Flow
Server-Side Generation
# Generate authentication options
options, state = server.authenticate_begin(
allow_credentials,
user_verification="preferred"
)
JSON Output Example
{
"publicKey": {
"challenge": "c29tZV9yYW5kb21fY2hhbGxlbmdl",
"rpId": "example.com",
"allowCredentials": [
{
"type": "public-key",
"id": "Y2xpZW50X2lkX2J5dGVz",
"transports": ["usb", "nfc", "ble"]
}
],
"timeout": 60000,
"userVerification": "preferred"
}
}
Advanced Configuration Example
Custom Algorithm Selection
# Server-side algorithm filtering
allowed_algorithms = [
PublicKeyCredentialParameters(type="public-key", alg=-50), # ML-DSA-87
PublicKeyCredentialParameters(type="public-key", alg=-49), # ML-DSA-65
PublicKeyCredentialParameters(type="public-key", alg=-7) # ES256
]
Extension Configuration
# Advanced extension support
extensions = {
"credBlob": "base64_encoded_blob",
"largeBlob": {"support": "preferred"},
"credProtect": {
"credentialProtectionPolicy": "userVerificationOptional",
"enforceCredentialProtectionPolicy": False
}
}
Section sources
Troubleshooting Guide
Common Issues and Solutions
Challenge Validation Failures
- Symptom: "Challenge mismatch" errors
- Cause: Incorrect challenge encoding or timing issues
- Solution: Ensure proper base64url encoding and synchronize timestamps
Binary Data Encoding Problems
- Symptom: "Invalid base64" errors
- Cause: Improper binary-to-text conversion
- Solution: Use platform-provided
websafe_encode()andwebsafe_decode()functions
Feature Flag Conflicts
- Symptom: JSON serialization inconsistencies
- Cause: Mixed feature flag configurations
- Solution: Standardize feature flag usage across server and client
Algorithm Compatibility Issues
- Symptom: "Unsupported algorithm" errors
- Cause: Client-server algorithm mismatch
- Solution: Verify algorithm support and implement fallback mechanisms
Debugging Tools
JSON Validation
# Validate JSON structure
import json
from fido2.webauthn import PublicKeyCredentialCreationOptions
try:
options_dict = json.loads(json_input)
options = PublicKeyCredentialCreationOptions.from_dict(options_dict)
print("Validation successful")
except Exception as e:
print(f"Validation failed: {e}")
Binary Data Inspection
# Inspect binary data encoding
from fido2.utils import websafe_encode, websafe_decode
binary_data = b"test_data"
encoded = websafe_encode(binary_data)
decoded = websafe_decode(encoded)
assert binary_data == decoded
Performance Considerations
Challenge Generation
- Optimization: Use cryptographically secure random number generators
- Size: Recommended challenge size: 16-32 bytes
- Expiration: Implement appropriate timeout mechanisms
Memory Management
- Large Objects: Use streaming for large credential collections
- Caching: Implement efficient caching for frequently accessed options
- Cleanup: Properly dispose of sensitive data after use
Network Efficiency
- Compression: Consider compression for large JSON payloads
- Caching: Implement HTTP caching for static options
- CDN: Use CDN for distributing static WebAuthn resources
Section sources