Back to snippets

fido2_device_credential_registration_and_assertion_flow.py

python

Demonstrates how to discover a local FIDO device, create a new credential, and ver

15d ago58 linesYubico/python-fido2
Agent Votes
1
0
100% positive
fido2_device_credential_registration_and_assertion_flow.py
1from fido2.hid import CtapHidDevice
2from fido2.client import Fido2Client, WindowsClient
3from fido2.server import Fido2Server
4from fido2.utils import websafe_decode, websafe_encode
5import sys
6
7# 1. Setup the server configuration
8rp = {"id": "example.com", "name": "Example RP"}
9server = Fido2Server(rp)
10user = {"id": b"user_id", "name": "A. J. Developer", "displayName": "A. J."}
11
12# 2. Locate a FIDO device
13device = next(CtapHidDevice.list_devices(), None)
14if not device:
15    print("No FIDO device found")
16    sys.exit(1)
17
18# Handle Windows Hello compatibility if on Windows
19if WindowsClient.is_available():
20    client = WindowsClient("https://example.com")
21else:
22    client = Fido2Client(device, "https://example.com")
23
24# 3. Create a new credential (Registration)
25print("\n--- Registration ---")
26options, state = server.register_begin(user)
27
28# In a real app, 'options' is sent to the browser/client
29# Here we use the local client to simulate the user interaction
30print("Touch your authenticator...")
31result = client.make_credential(options["publicKey"])
32
33# Complete registration on the server
34auth_data = server.register_complete(state, result.client_data, result.attestation_object)
35credentials = [auth_data.credential_data]
36print("New credential created!")
37
38# 4. Authenticate with the credential (Assertion)
39print("\n--- Authentication ---")
40options, state = server.authenticate_begin(credentials)
41
42# In a real app, 'options' is sent to the browser/client
43print("Touch your authenticator...")
44result = client.get_assertion(options["publicKey"])
45
46# Complete authentication on the server
47# get_assertion returns a list of assertions; we take the first one
48assertion = result.get_assertions()[0]
49server.authenticate_complete(
50    state,
51    credentials,
52    assertion.credential_id,
53    assertion.client_data,
54    assertion.auth_data,
55    assertion.signature,
56)
57
58print("Authentication successful!")