python-fido2

repository·main·Indexed 19 days ago

https://github.com/yubico/python-fido2

A FIDO2/WebAuthn library for implementing clients and servers. It enables communication with FIDO devices over USB (CTAP 1 and 2) and provides tools for verifying WebAuthn attestation and assertion signatures, featuring both low-level device access via CtapDevice and high-level abstractions for WebAuthn workflows.

Tokens
14K
Snippets
54
Records
64
Agent score
68%

What's inside python-fido2

  1. Run the WebAuthn Server Example

    main

    The fido2-example-server provides a minimal website demonstrating WebAuthn credential registration and authentication using python-fido2.

    Prerequisites

    Setup and Execution

    1. Navigate to the examples/server directory.
    2. Synchronize the environment using uv sync.
    3. Start the server using uv run server.
    4. Access the website at http://localhost:5000 using a WebAuthn-compatible browser.

    Security Note WebAuthn requires a secure context (HTTPS). While most browsers treat http://localhost as a secure context (allowing this demo to run without TLS), you must use HTTPS with a valid certificate in production environments.

    # Navigate to the example directory
    cd examples/server
    
    # Set up the environment
    uv sync
    
    # Run the server
    uv run server
  2. Run python-fido2 tests

    main

    The project uses uv for development. Most tests require a connected FIDO2 device.

    WARNING: These tests are destructive and will factory reset the device being tested. Tests are designed to only run on devices that appear to be in a newly reset state.

    uv run pytest
  3. Install python-fido2

    main

    Install the core library using pip. For NFC support, you must install the pcsc extra to include the necessary dependencies for PC/SC communication.

    # Standard installation
    pip install fido2
    
    # Installation with NFC support
    pip install fido2[pcsc]
  4. Update Fido2Server method parameters

    main
    The Fido2Server methods register_complete and authenticate_complete now strictly require RegistrationResponse and AuthenticationResponse objects. While these types were supported in version 1.1.0, the older method signatures that accepted previous response types are no longer supported in version 2.0.
  5. Import WindowsClient for cross-platform compatibility

    main

    The WindowsClient class has moved to fido2.client.windows and is no longer importable on non-Windows platforms. To prevent ImportError on MacOS or Linux, use a try/except block when importing.

    try:
        from fido2.client.windows import WindowsClient
        if WindowsClient.is_available():
            client = WindowsClient(...)
        else:
            # Handle Windows versions that do not support WindowsClient
            ...
    except ImportError:
        # Handle non-Windows platforms (e.g. MacOS, Linux)
        ...
  6. Configure Linux Udev rules for FIDO device access

    main

    To access FIDO devices on Linux without running as root, you must add a Udev rule to allow HID access. A common rule for Yubico devices is:

    KERNEL=="hidraw*", SUBSYSTEM=="hidraw", MODE="0664", GROUP="plugdev", ATTRS{idVendor}=="1050"

    Alternatively, check your distribution's package manager for existing U2F/FIDO2 rules.

    # Udev rule for allowing HID access to Yubico devices for FIDO support.
    
    KERNEL=="hidraw*", SUBSYSTEM=="hidraw", \
      MODE="0664", GROUP="plugdev", ATTRS{idVendor}=="1050"
  7. Handle updated return values for make_credential and get_assertion

    main

    The make_credential and get_assertion methods now return RegistrationResponse and AuthenticationResponse objects (from fido2.webauthn) instead of the previous authenticator response types. To access the underlying data (like client_data or attestation_object), you must now access the .response attribute of the returned object.

    These new response objects can be serialized to JSON by converting them to a dict. They can be deserialized using the .from_dict() method.

    # Serialization/Deserialization example
    import json
    from fido2.webauthn import RegistrationResponse
    
    result = client.make_credential(...)
    result_json = json.dumps(dict(result))  # Convert into a JSON
    
    result = RegistrationResponse.from_dict(json.loads(result_json))  # Deserialization
    
    # Accessing data from make_credential
    result = client.make_credential(...)
    response = result.response
    print(response.client_data, response.attestation_object)
    
    # Accessing data from get_assertion
    selection = client.get_assertion(...)
    result = selection.get_response(0)
    response = result.response
    print(response.client_data, response.authenticator_data, response.signature)
  8. Migrate Fido2Client and WindowsClient constructors

    main

    In version 2.0, the origin and verify parameters in Fido2Client and WindowsClient have been replaced by the client_data_collector parameter. You should use the DefaultClientDataCollector class to provide a one-to-one replacement for the old behavior. The verify parameter remains optional within the collector.

    from fido2.client import Fido2Client, DefaultClientDataCollector
    
    client = Fido2Client(
        device,
        client_data_collector=DefaultClientDataCollector(origin=origin, verify=verify_rp_id),
    )
  9. Register and Authenticate with the WebAuthn Example Website

    main

    The example server allows you to test the full WebAuthn lifecycle. Note that credentials are stored in-memory only; restarting the server will clear all registered credentials.

    Credential Registration

    1. Click the Register link on the website.
    2. Insert your U2F/FIDO2 Authenticator.
    3. Touch the physical button on the Authenticator to activate it.
    4. Confirm the success popup.

    Credential Authentication

    Note: You must successfully complete registration before attempting authentication.

    1. Click the Authenticate link on the website.
    2. Insert your U2F/FIDO2 Authenticator.
    3. Touch the physical button on the Authenticator.
    4. Confirm the success popup.
  10. Serialize and deserialize WebAuthn data classes

    main

    Most WebAuthn data classes in this module can be converted to JSON-compatible dictionaries using dict() and reconstructed using the .from_dict(data) method. This is useful for transmitting data between a server and a client via JSON.

    Example:

    user = PublicKeyCredentialUserEntity(id=b"1234", name="Alice")
    data = dict(user)
    # data is now a JSON-compatible dictionary
    user2 = PublicKeyCredentialUserEntity.from_dict(data)
    assert user == user2
    user = PublicKeyCredentialUserEntity(id=b"1234", name="Alice")
    data = dict(user)
    user2 = PublicKeyCredentialUserEntity.from_dict(data)