-
Notifications
You must be signed in to change notification settings - Fork 0
Request Options Schemas
- 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
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.
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
- fido2/webauthn.py
Section sources
- fido2/webauthn.py
The PublicKeyCredentialCreationOptions class defines the parameters for credential registration requests, enabling users to create new WebAuthn credentials.
| 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 |
-
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
-
Type:
PublicKeyCredentialUserEntity - Purpose: Contains user identification and profile information
-
Required Fields:
name(string),id(bytes) -
Optional Fields:
display_name(string)
-
Type:
bytes - Purpose: Random data used to prevent replay attacks
- Requirements: Must be cryptographically secure random bytes
- Encoding: Automatically base64url-encoded during JSON serialization
-
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
- fido2/webauthn.py
The PublicKeyCredentialRequestOptions class defines the parameters for authentication requests, enabling users to verify their identity using existing WebAuthn credentials.
| 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 |
-
Type:
bytes - Purpose: Unique data for each authentication request
- Security: Must be unpredictable and securely generated
- Expiration: Typically valid for short duration (seconds)
-
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
-
Type:
Optional[Sequence[PublicKeyCredentialDescriptor>] - Purpose: Restricts authentication to specific credentials
-
Structure: Each descriptor contains
type,id, and optionaltransports
-
Type:
Optional[UserVerificationRequirement] -
Values:
REQUIRED,PREFERRED,DISCOURAGED - Purpose: Controls whether user verification is mandatory
Section sources
- fido2/webauthn.py
- Representation: Raw binary data for cryptographic material
- Serialization: Automatically base64url-encoded to JSON strings
- Validation: Length-dependent based on cryptographic algorithm requirements
- Definition: Fields that may be omitted in requests
-
Implementation: Uses Python
Optional[T]typing annotation -
Default Behavior: Serialized as
nullin JSON when absent
-
UserVerificationRequirement:
REQUIRED,PREFERRED,DISCOURAGED -
AttestationConveyancePreference:
NONE,INDIRECT,DIRECT,ENTERPRISE -
AuthenticatorAttachment:
PLATFORM,CROSS_PLATFORM -
ResidentKeyRequirement:
REQUIRED,PREFERRED,DISCOURAGED
-
Fields:
type(always "public-key"),alg(algorithm identifier) - Purpose: Specifies supported cryptographic algorithms
-
Example Values:
-7(ES256),-257(RS256),-48(ML-DSA-44)
-
Fields:
type(always "public-key"),id(credential identifier),transports(optional) - Purpose: References existing credentials for authentication
- Credential ID: Base64url-encoded binary identifier
Section sources
- fido2/webauthn.py
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
- fido2/utils.py
- fido2/webauthn.py
The platform provides two core functions for binary-to-text encoding:
- 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
- Purpose: Converts URL-safe base64 string back to binary data
- Implementation: Handles automatic padding calculation
- Compatibility: Supports both legacy and modern base64url formats
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
- fido2/utils.py
- fido2/features.py
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 = FalseThe 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:
passThe 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/server/config.py
- fido2/features.py
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
- server/server/routes/simple.py
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
- server/server/routes/simple.py
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
- server/server/routes/advanced.py
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
]
}
});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, "");
}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
- server/server/static/scripts/shared/webauthn-json.browser-ponyfill.js
# Generate registration options
options, state = server.register_begin(
PublicKeyCredentialUserEntity(
id=b"user_id_bytes",
name="username@example.com",
display_name="User Display Name"
),
existing_credentials,
user_verification="preferred",
authenticator_attachment="cross-platform"
){
"publicKey": {
"rp": {
"name": "Example Service",
"id": "example.com"
},
"user": {
"name": "username@example.com",
"displayName": "User Display Name",
"id": "dXNlcm5hbWVAZXhhbXBsZS5jb20="
},
"challenge": "c29tZV9yYW5kb21fY2hhbGxlbmdl",
"pubKeyCredParams": [
{"type": "public-key", "alg": -7},
{"type": "public-key", "alg": -257}
],
"timeout": 60000,
"attestation": "direct"
}
}# Generate authentication options
options, state = server.authenticate_begin(
allow_credentials,
user_verification="preferred"
){
"publicKey": {
"challenge": "c29tZV9yYW5kb21fY2hhbGxlbmdl",
"rpId": "example.com",
"allowCredentials": [
{
"type": "public-key",
"id": "Y2xpZW50X2lkX2J5dGVz",
"transports": ["usb", "nfc", "ble"]
}
],
"timeout": 60000,
"userVerification": "preferred"
}
}# 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
]# Advanced extension support
extensions = {
"credBlob": "base64_encoded_blob",
"largeBlob": {"support": "preferred"},
"credProtect": {
"credentialProtectionPolicy": "userVerificationOptional",
"enforceCredentialProtectionPolicy": False
}
}Section sources
- tests/test_webauthn.py
- Symptom: "Challenge mismatch" errors
- Cause: Incorrect challenge encoding or timing issues
- Solution: Ensure proper base64url encoding and synchronize timestamps
- Symptom: "Invalid base64" errors
- Cause: Improper binary-to-text conversion
-
Solution: Use platform-provided
websafe_encode()andwebsafe_decode()functions
- Symptom: JSON serialization inconsistencies
- Cause: Mixed feature flag configurations
- Solution: Standardize feature flag usage across server and client
- Symptom: "Unsupported algorithm" errors
- Cause: Client-server algorithm mismatch
- Solution: Verify algorithm support and implement fallback mechanisms
# 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}")# 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- Optimization: Use cryptographically secure random number generators
- Size: Recommended challenge size: 16-32 bytes
- Expiration: Implement appropriate timeout mechanisms
- Large Objects: Use streaming for large credential collections
- Caching: Implement efficient caching for frequently accessed options
- Cleanup: Properly dispose of sensitive data after use
- Compression: Consider compression for large JSON payloads
- Caching: Implement HTTP caching for static options
- CDN: Use CDN for distributing static WebAuthn resources
Section sources
- fido2/webauthn.py
- fido2/utils.py