Lab - Authentication with FIDO2

Slides

Download here

Introduction

FIDO2 is a modern authentication standard aimed at improving online security by eliminating the reliance on passwords and providing more robust and straightforward authentication methods. Created by the FIDO (Fast IDentity Online) Alliance, FIDO2 is part of a collective initiative to replace traditional password-based logins with more secure alternatives, such as passwordless or multifactor authentication (MFA).

FIDO2 is an umbrella term for two main technical components: (1) The WebAuthn (Web Authentication API), developed by the World Wide Web Consortium (W3C), allows browsers and applications to authenticate users via public-key cryptography. With WebAuthn, online services can register and authenticate users using their public keys without ever needing to store passwords. (2) The CTAP (Client to Authenticator Protocol) allows external devices, such as USB keys, mobile devices, or biometric devices (like fingerprint readers), to communicate securely with browsers and applications for authentication purposes.

In this guide we will explore the passwordless login features that WebAuthn provides.

Setup

In order to experiment with FIDO2 and WebAuthn we need both a client side (i.e., authenticator token) and a server-side (i.e., authenticating application). We will begin by setting up the environment.

Complete Annex A: environment setup before starting these exercises. Use Firefox, KeePassXC and the application inside the same VM, and open exactly http://localhost:5000/.

Exploring the web app

The most important methods (now missing) should be implemented in src/app.py. Please open that file in your favorite editor and locate the missing code.

Registration works in two steps: first, generate the creation options, then validate the client’s response and store the credential. Authentication follows the same request/verification pattern.

After completing registration, click Register and inspect Debug Info: the verification response should contain "verified": true. After completing authentication, click Authenticate and expect the same result. Keep the browser’s Network panel open to inspect each options request and verification response. Explain which values the server stores and which key remains with the authenticator.

General considerations

Even though the default Flask configuration should work as-is, when creating your web app beware of the relevant Flask configurations.

The py_webauthn module exposes a few crucial methods, which we will explore in the following subsections:

generate_registration_options()
verify_registration_response()
generate_authentication_options()
verify_authentication_response()

Make sure to read the documentation here for more information.

The examples below use py_webauthn 2.x. Add these imports to src/app.py:

from webauthn.helpers import (
    parse_registration_credential_json,
    parse_authentication_credential_json,
)
from webauthn.helpers.structs import (
    AuthenticatorTransport,
    PublicKeyCredentialDescriptor,
)

The scaffold stores user IDs as strings; encode the ID as bytes when generating registration options. Credential descriptors are typed objects, and the JSON parsers above replace the old .parse_raw() calls. Keep the scaffold’s TODOs until you reach the corresponding exercise.

Registration

Create credential

In broad terms, the process works as follows:

  • Client retrieves PublicKeyCredentialCreationOptions from server; state/challenge must be preserved on the server side.
  • Client/navigator calls authenticator with options to create credential.
  • Authenticator will create new credential and return an attestation response (new credential’s public key + metadata).

Example from the documentation.

Implement handler_generate_registration_options() in src/app.py:

@app.route("/generate-registration-options", methods=["GET"])
def handler_generate_registration_options():
    global current_registration_challenge
    global logged_in_user_id

    user = in_memory_db[logged_in_user_id]

    options = generate_registration_options(
        rp_id=rp_id,
        rp_name=rp_name,
        user_id=user.id.encode("utf-8"),
        user_name=user.username,
        exclude_credentials=[
            PublicKeyCredentialDescriptor(
                id=cred.id,
                transports=[AuthenticatorTransport(t) for t in cred.transports],
            )
            for cred in user.credentials
        ],
        authenticator_selection=AuthenticatorSelectionCriteria(
            user_verification=UserVerificationRequirement.REQUIRED
        ),
        supported_pub_key_algs=[
            COSEAlgorithmIdentifier.ECDSA_SHA_256,
            COSEAlgorithmIdentifier.RSASSA_PKCS1_v1_5_SHA_256,
        ],
    )

    current_registration_challenge = options.challenge

    return app.response_class(options_to_json(options), mimetype="application/json")
Register credential

In broad terms, the credential registration process works as follows:

  • The browser helper serializes the credential as JSON, encoding binary fields with base64url.
  • The response includes the CBOR-encoded attestation object and is sent to the server for registration.
  • Server verifies the attestation and stores credential public key and association with the user.

Example from the documentation.

Implement handler_verify_registration_response() in src/app.py:

@app.route("/verify-registration-response", methods=["POST"])
def handler_verify_registration_response():
    global current_registration_challenge
    global logged_in_user_id

    body = request.get_data()
    challenge = current_registration_challenge
    current_registration_challenge = None
    if challenge is None:
        return {"verified": False, "msg": "Start a new registration"}, 400

    try:
        credential = parse_registration_credential_json(body.decode("utf-8"))
        verification = verify_registration_response(
            credential=credential,
            expected_challenge=challenge,
            expected_rp_id=rp_id,
            expected_origin=origin,
            require_user_verification=True,
        )
        transports = credential.response.transports or [
            AuthenticatorTransport(t)
            for t in json.loads(body).get("transports", [])
        ]
    except Exception as err:
        return {"verified": False, "msg": str(err)}, 400

    user = in_memory_db[logged_in_user_id]

    new_credential = Credential(
        id=verification.credential_id,
        public_key=verification.credential_public_key,
        sign_count=verification.sign_count,
        transports=[t.value for t in transports],
    )

    user.credentials.append(new_credential)

    return {"verified": True}

Authentication

Create assertion

In broad terms, the process works as follows:

  • Client retrieves PublicKeyCredentialRequestOptions from server; state/challenge has to be preserved on the server side.
  • Client/navigator calls authenticator with options to generate assertion.

Example from the documentation.

Implement handler_generate_authentication_options() in src/app.py:

@app.route("/generate-authentication-options", methods=["GET"])
def handler_generate_authentication_options():
    global current_authentication_challenge
    global logged_in_user_id

    user = in_memory_db[logged_in_user_id]

    options = generate_authentication_options(
        rp_id=rp_id,
        allow_credentials=[
            PublicKeyCredentialDescriptor(
                id=cred.id,
                transports=[AuthenticatorTransport(t) for t in cred.transports],
            )
            for cred in user.credentials
        ],
        user_verification=UserVerificationRequirement.REQUIRED,
    )

    current_authentication_challenge = options.challenge

    return app.response_class(options_to_json(options), mimetype="application/json")
Authenticate (using) assertion

In broad terms, the final authentication process works as follows:

  • The browser helper serializes the assertion as JSON, encoding binary fields with base64url.
  • The assertion is sent to the server for authentication.
  • Server validates the assertion (challenge, signature) against registered user credentials and performs logon process on success.

Example from the documentation.

Implement hander_verify_authentication_response() in src/app.py:

@app.route("/verify-authentication-response", methods=["POST"])
def hander_verify_authentication_response():
    global current_authentication_challenge
    global logged_in_user_id

    body = request.get_data()
    challenge = current_authentication_challenge
    current_authentication_challenge = None
    if challenge is None:
        return {"verified": False, "msg": "Start a new authentication"}, 400

    try:
        credential = parse_authentication_credential_json(body.decode("utf-8"))

        # Find the user's corresponding public key
        user = in_memory_db[logged_in_user_id]
        user_credential = None
        for _cred in user.credentials:
            if _cred.id == credential.raw_id:
                user_credential = _cred

        if user_credential is None:
            raise Exception("Could not find corresponding public key in DB")

        # Verify the assertion
        verification = verify_authentication_response(
            credential=credential,
            expected_challenge=challenge,
            expected_rp_id=rp_id,
            expected_origin=origin,
            credential_public_key=user_credential.public_key,
            credential_current_sign_count=user_credential.sign_count,
            require_user_verification=True,
        )
    except Exception as err:
        return {"verified": False, "msg": str(err)}, 400

    # Update our credential's sign count to what the authenticator says it is now
    user_credential.sign_count = verification.new_sign_count

    return {"verified": True}

Each verification attempt consumes its challenge, including failed attempts. Start a new operation before retrying. Compare a successful response with one whose challenge or origin does not match: should a valid signature alone allow login?

Extra

Try the server code with a different client such as Windows Hello, a FIDO2 USB token such as Yubikey, Nitrokey FIDO2, or Thetis. Other devices are optional extensions. A remote browser needs a separately configured HTTPS origin and matching RP ID; the localhost setup below is for a browser inside the VM.

Bibliography

https://www.w3.org/TR/webauthn-2/

https://fidoalliance.org/fido2/

Tutorial + Code: https://duo.com/blog/going-passwordless-with-py-webauthn

Authors: Vitor Cunha, Pedro Escaleira

Annex A: environment setup

Client-side

Use the KeePassXC for the client-side. Later, you may also use Windows Hello, Android, Apple Keychain, Yubikey, or other commercially-graded solutions.

Install KeepassXC (version 2.7.7 or higher) in the VM:

sudo apt update
sudo apt install keepassxc
keepassxc --version

The course Ubuntu 26.04 package meets this version requirement; no PPA is needed. Create a separate KeePassXC database for lab credentials and keep it unlocked. Now, go to Tools –> Settings, and enable the browser integration for Firefox. Within the browser integration settings, go to Advanced and enable “Allow using localhost with passkeys.”

If Firefox cannot connect to KeePassXC, try the official Mozilla Firefox build using the local installation instructions. Choose the archive for the VM architecture (uname -m): Linux ARM64 for aarch64, Linux 64-bit for x86_64. Extract it into a separate lab8-client folder in your home directory. Create a profile folder there and launch the extracted binary from a VM terminal:

~/lab8-client/firefox/firefox --no-remote --profile ~/lab8-client/profile

Use this separate browser for the extension and both test sites below. The 09-11-2026 ARM64 validation passed with Mozilla Firefox 159.0.1, KeePassXC 2.7.10 and KeePassXC-Browser 1.10.4.1; Firefox Snap 157 did not connect in that run. Other browser builds and architectures require their own check.

Launch Firefox and install the KeePassXC-Browser plugin. Connect the plugin to your running KeePassXC, giving a name to your browser connection.

Go to the KeePassXC-Browser settings and tick the “Enable passkeys” option.

Now, test the passkey functionality using the yubico test website. You must first enroll your password manager like a new user was created. Only then can you authenticate your user using the passkey functionality.

You should reach the authentication successful webpage before moving forward in this step.

Server-side

Now that we have a functioning authenticator (the password manager) we will explore this protocol within a webserver application. To implement the server-side, when you already have a web application and want to add FIDO2 functionality, we recommend using the py_webauthn module by Cisco Duo Labs.

For this guide, we will use the py_webauthn module creators demonstration, with a few crucial methods removed so that you can learn how that process works.

## Lets clone the remote repository
$ git clone https://github.com/vitorcunha/sio_fido2-webathn.git fido2-demo

## enter the folder for the server demo code
$ cd fido2-demo
$ git checkout 557cee89cd4ab7b3492ce28367a5d36f07148e3a

## Install the environment prerequisites (already provided by the course VM)
$ sudo apt install python3-venv python3-dev build-essential \
    libffi-dev libssl-dev

## Create an isolated Python environment
$ python3 -m venv venv

## Activate the environment
$ source venv/bin/activate

Replace the cloned project’s requirements.txt with the following course pins (also maintained in Guioes/_fido2/requirements.txt in the teaching repository). The original dependency set does not install correctly on Python 3.14.

blinker==1.9.0
cbor2==5.9.0
cffi==2.1.1
click==8.5.0
cryptography==50.0.1
Flask==3.1.3
itsdangerous==2.2.0
Jinja2==3.1.6
MarkupSafe==3.0.3
pyasn1==0.6.4
pyasn1_modules==0.4.2
pycparser==3.0
pyOpenSSL==26.4.0
webauthn==2.8.0
Werkzeug==3.1.8
$ python -m pip install -r requirements.txt
$ python -m pip check
$ python -m flask --app src.app run --host localhost --reload

The explicit --reload option reloads the server when you save your exercise code. Flask 3 ignores the old startup script’s FLASK_ENV setting. Reloading also clears the demonstration’s in-memory credentials; register again afterward.

Before using the registration buttons, adapt the pinned scaffold’s browser library to the WebAuthn 2.x JSON encoding. Run this once from fido2-demo/:

python - <<'PYTHON'
from pathlib import Path

path = Path("src/static/simplewebauthn-browser.4.1.0.umd.min.js")
source = path.read_text()
changes = {
    "id:(a=e.user.id,(new TextEncoder).encode(a))": "id:n(e.user.id)",
    'w=new TextDecoder("utf-8").decode(h)': "w=t(h)",
}
for old, new in changes.items():
    if source.count(old) != 1:
        raise SystemExit(
            "Expected pinned browser library; already patched or different version"
        )
    source = source.replace(old, new)
path.write_text(source)
PYTHON

This decodes the registration user ID from base64url to bytes and encodes the returned authentication user handle back to base64url. Refresh the browser without its cache after applying the change. Keep using localhost:5000 for this exercise.

If you follow http://localhost:5000/ you should be greeted with the following page:

webapp

WARNING: The Web app will not work correctly at this stage!

Reset and troubleshooting

  • If the extension cannot connect, check Firefox browser integration in KeePassXC, extension pairing, an unlocked database, and both passkey settings. In a sandboxed browser, check native messaging support before changing the Python code.
  • Keep using localhost, not 127.0.0.1 or a VM IP address: the scaffold expects RP ID localhost and origin http://localhost:5000.
  • The four unimplemented handlers are intentional exercises. The home page loading does not mean registration and authentication already work.
  • Stop Flask with Ctrl+C. Restarting/reloading clears its in-memory credentials. Register again; if the old passkey remains in the lab database, delete that lab entry or use a new lab database. KeePassXC may instead show “Existing passkey found”: choose Update, then Overwrite only for that disposable lab credential. A locked database can prevent passkey selection.
  • A failed verification consumes the challenge. Use Register or Authenticate again to obtain a fresh challenge before retrying.
Previous
Next