Skip to content

Instantly share code, notes, and snippets.

@samuelcolvin
Created November 17, 2021 22:32
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save samuelcolvin/3ff019aa738aa558a185c4fb002b5751 to your computer and use it in GitHub Desktop.
Save samuelcolvin/3ff019aa738aa558a185c4fb002b5751 to your computer and use it in GitHub Desktop.
demo of webauthn using FastAPI
const log_el = document.getElementById('log')
function log(...messages) {
console.log(...messages)
log_el.innerText += '\n' + messages.map(m => JSON.stringify(m, null, 2)).join(' ')
}
function error(message) {
console.error(message)
log_el.innerText += '\n' + message
throw Error('got error:' + message)
}
const asArrayBuffer = v => Uint8Array.from(atob(v.replace(/_/g, '/').replace(/-/g, '+')), c => c.charCodeAt(0))
const asBase64 = ab => btoa(String.fromCharCode(...new Uint8Array(ab)))
async function getPublicKey(path, element) {
const user_id = document.getElementById(element).value
const r = await fetch(`/${path}/${user_id}/`)
if (r.status !== 200) {
error(`Unexpected response ${r.status}: ${await r.text()}`)
}
return await r.json()
}
async function post(path, element, creds) {
const user_id = document.getElementById(element).value
const {attestationObject, clientDataJSON, signature, authenticatorData} = creds.response
const data = {
id: creds.id,
rawId: asBase64(creds.rawId),
response: {
attestationObject: asBase64(attestationObject),
clientDataJSON: asBase64(clientDataJSON),
}
}
if (signature) {
data.response.signature = asBase64(signature)
data.response.authenticatorData = asBase64(authenticatorData)
}
const r2 = await fetch(`/${path}/${user_id}/`, {
method: 'POST',
body: JSON.stringify(data),
headers: {'content-type': 'application/json'}
})
if (r2.status !== 200) {
error(`Unexpected response ${r2.status}: ${await r2.text()}`)
}
}
async function register() {
const publicKey = await getPublicKey('register', 'user-id-register')
console.log('register get response:', publicKey)
publicKey.user.id = asArrayBuffer(publicKey.user.id)
publicKey.challenge = asArrayBuffer(publicKey.challenge)
let creds
try {
creds = await navigator.credentials.create({publicKey})
} catch (err) {
log('refused:', err.toString())
return
}
await post('register', 'user-id-register', creds)
log('registration successful')
}
async function authenticate() {
const publicKey = await getPublicKey('auth', 'user-id-auth')
console.log('auth get response:', publicKey)
publicKey.challenge = asArrayBuffer(publicKey.challenge)
publicKey.allowCredentials[0].id = asArrayBuffer(publicKey.allowCredentials[0].id)
let creds
try {
creds = await navigator.credentials.get({publicKey})
} catch (err) {
log('refused:', err.toString())
return
}
await post('auth', 'user-id-auth', creds)
log('authentication successful')
}
import base64
from pathlib import Path
import webauthn
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import HTMLResponse
from pydantic import validator
from starlette.middleware import Middleware
from starlette.middleware.sessions import SessionMiddleware
from webauthn.helpers.structs import (
RegistrationCredential,
PublicKeyCredentialCreationOptions,
PublicKeyCredentialRequestOptions,
AuthenticationCredential,
UserVerificationRequirement,
AuthenticatorSelectionCriteria,
AuthenticatorAttachment,
ResidentKeyRequirement,
PublicKeyCredentialDescriptor,
AuthenticatorTransport,
)
# secrets.token_hex()
secret_key = '9c580e0641762c32eab407257d924c25d5c8dd44a67d9efb4403038ae783c37c'
middleware = [
Middleware(
SessionMiddleware,
secret_key=secret_key,
session_cookie='webauthn-demo',
same_site='strict',
https_only=True,
)
]
app = FastAPI(middleware=middleware)
@app.get('/', response_class=HTMLResponse)
async def index():
# language=HTML
return """
<h1>Webauthn demo</h1>
<div style="display: flex; justify-content: space-around">
<div style="border: 1px solid black; padding: 10px">
<h2>Register</h2>
<label for="user-id-register">User ID:</label>
<input type="number" step="1" id="user-id-register"/>
<button onclick="register()">Register</button>
</div>
<div style="border: 1px solid black; padding: 10px">
<h2>Authenticate</h2>
<label for="user-id-auth">User ID:</label>
<input type="number" step="1" id="user-id-auth"/>
<button onclick="authenticate()">Authenticate</button>
</div>
</div>
<pre id="log"></pre>
<script src="/webauthn_client.js"></script>
"""
class JavascriptResponse(HTMLResponse):
media_type = 'application/javascript'
@app.get('/webauthn_client.js', response_class=JavascriptResponse)
async def client_js():
return Path('webauthn_client.js').read_bytes()
@app.get('/register/{user_id:int}/', response_model=PublicKeyCredentialCreationOptions)
async def register_get(request: Request, user_id: int):
public_key = webauthn.generate_registration_options(
rp_id='localhost',
rp_name='MyCompanyName',
user_id=str(user_id),
user_name=f'{user_id}@example.com',
user_display_name='Samuel Colvin',
authenticator_selection=AuthenticatorSelectionCriteria(
authenticator_attachment=AuthenticatorAttachment.CROSS_PLATFORM,
resident_key=ResidentKeyRequirement.DISCOURAGED,
user_verification=UserVerificationRequirement.DISCOURAGED,
),
)
request.session['webauthn_register_challenge'] = base64.b64encode(public_key.challenge).decode()
return public_key
def b64decode(s: str) -> bytes:
return base64.urlsafe_b64decode(s.encode())
class CustomRegistrationCredential(RegistrationCredential):
@validator('raw_id', pre=True)
def convert_raw_id(cls, v: str):
assert isinstance(v, str), 'raw_id is not a string'
return b64decode(v)
@validator('response', pre=True)
def convert_response(cls, data: dict):
assert isinstance(data, dict), 'response is not a dictionary'
return {k: b64decode(v) for k, v in data.items()}
auth_database = {}
@app.post('/register/{user_id:int}/')
async def register_post(request: Request, user_id: int, credential: CustomRegistrationCredential):
expected_challenge = base64.b64decode(request.session['webauthn_register_challenge'].encode())
registration = webauthn.verify_registration_response(
credential=credential,
expected_challenge=expected_challenge,
expected_rp_id='localhost',
expected_origin='http://localhost:8000',
)
auth_database[user_id] = {
'public_key': registration.credential_public_key,
'sign_count': registration.sign_count,
'credential_id': registration.credential_id,
}
debug(registration)
@app.get('/auth/{user_id:int}/', response_model=PublicKeyCredentialRequestOptions)
async def auth_get(request: Request, user_id: int):
try:
user_creds = auth_database[user_id]
except KeyError:
raise HTTPException(status_code=404, detail='user not found')
public_key = webauthn.generate_authentication_options(
rp_id='localhost',
allow_credentials=[
PublicKeyCredentialDescriptor(id=user_creds['credential_id'], transports=[AuthenticatorTransport.USB])
],
user_verification=UserVerificationRequirement.DISCOURAGED,
)
request.session['webauthn_auth_challenge'] = base64.b64encode(public_key.challenge).decode()
return public_key
class CustomAuthenticationCredential(AuthenticationCredential):
@validator('raw_id', pre=True)
def convert_raw_id(cls, v: str):
assert isinstance(v, str), 'raw_id is not a string'
return b64decode(v)
@validator('response', pre=True)
def convert_response(cls, data: dict):
assert isinstance(data, dict), 'response is not a dictionary'
return {k: b64decode(v) for k, v in data.items()}
@app.post('/auth/{user_id:int}/')
async def auth_post(request: Request, user_id: int, credential: CustomAuthenticationCredential):
expected_challenge = base64.b64decode(request.session['webauthn_auth_challenge'].encode())
try:
user_creds = auth_database[user_id]
except KeyError:
raise HTTPException(status_code=404, detail='user not found')
auth = webauthn.verify_authentication_response(
credential=credential,
expected_challenge=expected_challenge,
expected_rp_id='localhost',
expected_origin='http://localhost:8000',
credential_public_key=user_creds['public_key'],
credential_current_sign_count=user_creds['sign_count'],
)
debug(auth)
user_creds['sign_count'] = auth.new_sign_count
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment