🔒 Security

WebAuthn

Web Authentication API

A web authentication API standardized by the W3C and FIDO Alliance. Implements strong passwordless authentication on the web using biometrics, security keys, and more. It fundamentally blocks phishing attacks and is the foundation technology of Passkeys.

📖 Detailed Explanation

WebAuthn (Web Authentication) is a web standard authentication API jointly developed by the W3C and the FIDO Alliance. It was designed to solve the fundamental limitations of password-based authentication (phishing, credential stuffing, and reuse attacks). Based on public-key cryptography, it stores the private key securely on the user's device and sends only the public key to the server. Thanks to this structure, user credentials are not leaked even if the server is hacked.

The core concept of WebAuthn is the authenticator. A platform authenticator uses the biometrics built into the device (Face ID, Touch ID, Windows Hello), while a roaming authenticator uses an external security key such as a YubiKey. The user is verified through a challenge-response process, and a unique key pair is generated for each site, which makes cross-site tracking impossible.

As a core component of the FIDO2 protocol, WebAuthn handles the browser API, while CTAP (Client to Authenticator Protocol) handles communication between the device and the authenticator. Since 2023, Apple, Google, and Microsoft have joined forces to popularize it under the brand name 'Passkey.' Passkeys sync WebAuthn credentials through the cloud, so the same credentials can be used across multiple devices.

WebAuthn is especially important in AI/ML systems. It provides strong passwordless authentication for sensitive operations such as model training pipelines, data access, and inference API calls. Using hardware-based authentication instead of passwords, which are vulnerable to automated attacks, effectively blocks unauthorized access to ML assets. In enterprise MLOps platforms, WebAuthn MFA is becoming a mandatory security requirement.

💻 Code Example

// WebAuthn 등록 (Registration) - 브라우저
async function registerWebAuthn(username) {
    // 서버에서 챌린지와 사용자 정보 요청
    const response = await fetch('/api/webauthn/register/options', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username })
    });
    const options = await response.json();

    // Base64URL 디코딩
    options.challenge = base64urlToBuffer(options.challenge);
    options.user.id = base64urlToBuffer(options.user.id);

    // 브라우저 WebAuthn API 호출 - 생체인식/보안키 프롬프트
    const credential = await navigator.credentials.create({
        publicKey: {
            rp: {
                name: "KAITRUST",
                id: "kaitrust.ai"  // 도메인에 바인딩
            },
            user: {
                id: options.user.id,
                name: username,
                displayName: username
            },
            challenge: options.challenge,
            pubKeyCredParams: [
                { type: "public-key", alg: -7 },   // ES256
                { type: "public-key", alg: -257 }  // RS256
            ],
            authenticatorSelection: {
                authenticatorAttachment: "platform",  // 내장 인증기
                userVerification: "required",         // 생체인증 필수
                residentKey: "required"               // 패스키 지원
            },
            timeout: 60000,
            attestation: "none"  // 개인정보 보호
        }
    });

    // 서버로 크레덴셜 전송
    const attestationResponse = {
        id: credential.id,
        rawId: bufferToBase64url(credential.rawId),
        type: credential.type,
        response: {
            clientDataJSON: bufferToBase64url(credential.response.clientDataJSON),
            attestationObject: bufferToBase64url(credential.response.attestationObject)
        }
    };

    await fetch('/api/webauthn/register/verify', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(attestationResponse)
    });

    console.log('✅ WebAuthn 등록 완료');
}

// WebAuthn 인증 (Authentication) - 브라우저
async function authenticateWebAuthn() {
    const response = await fetch('/api/webauthn/authenticate/options');
    const options = await response.json();

    options.challenge = base64urlToBuffer(options.challenge);

    const assertion = await navigator.credentials.get({
        publicKey: {
            challenge: options.challenge,
            rpId: "kaitrust.ai",
            userVerification: "required",
            timeout: 60000
        }
    });

    // 서버로 어설션 전송
    const assertionResponse = {
        id: assertion.id,
        rawId: bufferToBase64url(assertion.rawId),
        type: assertion.type,
        response: {
            clientDataJSON: bufferToBase64url(assertion.response.clientDataJSON),
            authenticatorData: bufferToBase64url(assertion.response.authenticatorData),
            signature: bufferToBase64url(assertion.response.signature),
            userHandle: assertion.response.userHandle
                ? bufferToBase64url(assertion.response.userHandle)
                : null
        }
    };

    const result = await fetch('/api/webauthn/authenticate/verify', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(assertionResponse)
    });

    return result.json();
}
// WebAuthn 서버 구현 - Node.js (SimpleWebAuthn 라이브러리)
import {
    generateRegistrationOptions,
    verifyRegistrationResponse,
    generateAuthenticationOptions,
    verifyAuthenticationResponse
} from '@simplewebauthn/server';

const rpName = 'KAITRUST';
const rpID = 'kaitrust.ai';
const origin = 'https://kaitrust.ai';

// 등록 옵션 생성
app.post('/api/webauthn/register/options', async (req, res) => {
    const { username } = req.body;
    const user = await db.findOrCreateUser(username);

    const options = await generateRegistrationOptions({
        rpName,
        rpID,
        userID: user.id,
        userName: username,
        userDisplayName: username,
        attestationType: 'none',
        authenticatorSelection: {
            authenticatorAttachment: 'platform',
            userVerification: 'required',
            residentKey: 'required'
        },
        supportedAlgorithmIDs: [-7, -257]  // ES256, RS256
    });

    // 챌린지 임시 저장 (세션 또는 Redis)
    await redis.set(`webauthn:challenge:${user.id}`, options.challenge, 'EX', 300);

    res.json(options);
});

// 등록 검증
app.post('/api/webauthn/register/verify', async (req, res) => {
    const { body } = req;
    const user = req.session.user;
    const expectedChallenge = await redis.get(`webauthn:challenge:${user.id}`);

    try {
        const verification = await verifyRegistrationResponse({
            response: body,
            expectedChallenge,
            expectedOrigin: origin,
            expectedRPID: rpID
        });

        if (verification.verified) {
            // 공개키 저장
            await db.saveCredential({
                credentialID: verification.registrationInfo.credentialID,
                credentialPublicKey: verification.registrationInfo.credentialPublicKey,
                counter: verification.registrationInfo.counter,
                userId: user.id
            });

            res.json({ success: true });
        }
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

// 인증 옵션 생성
app.get('/api/webauthn/authenticate/options', async (req, res) => {
    const options = await generateAuthenticationOptions({
        rpID,
        userVerification: 'required',
        timeout: 60000
    });

    await redis.set(`webauthn:auth:challenge`, options.challenge, 'EX', 300);
    res.json(options);
});

// 인증 검증
app.post('/api/webauthn/authenticate/verify', async (req, res) => {
    const { body } = req;
    const expectedChallenge = await redis.get(`webauthn:auth:challenge`);
    const credential = await db.findCredential(body.id);

    const verification = await verifyAuthenticationResponse({
        response: body,
        expectedChallenge,
        expectedOrigin: origin,
        expectedRPID: rpID,
        authenticator: {
            credentialID: credential.credentialID,
            credentialPublicKey: credential.credentialPublicKey,
            counter: credential.counter
        }
    });

    if (verification.verified) {
        // 카운터 업데이트 (리플레이 공격 방지)
        await db.updateCredentialCounter(
            credential.id,
            verification.authenticationInfo.newCounter
        );

        // JWT 토큰 발급
        const token = jwt.sign({ userId: credential.userId }, process.env.JWT_SECRET);
        res.json({ success: true, token });
    }
});
# WebAuthn 서버 검증 - Python (py_webauthn 라이브러리)
from webauthn import (
    generate_registration_options,
    verify_registration_response,
    generate_authentication_options,
    verify_authentication_response,
    options_to_json
)
from webauthn.helpers.structs import (
    AuthenticatorSelectionCriteria,
    UserVerificationRequirement,
    ResidentKeyRequirement,
    PublicKeyCredentialDescriptor
)
import json

RP_ID = "kaitrust.ai"
RP_NAME = "KAITRUST"
ORIGIN = "https://kaitrust.ai"

# 등록 옵션 생성
def create_registration_options(user_id: str, username: str):
    options = generate_registration_options(
        rp_id=RP_ID,
        rp_name=RP_NAME,
        user_id=user_id.encode(),
        user_name=username,
        user_display_name=username,
        authenticator_selection=AuthenticatorSelectionCriteria(
            user_verification=UserVerificationRequirement.REQUIRED,
            resident_key=ResidentKeyRequirement.REQUIRED
        )
    )
    # 챌린지 저장 (Redis 또는 세션)
    redis_client.setex(
        f"webauthn:register:{user_id}",
        300,
        options.challenge
    )
    return options_to_json(options)

# 등록 응답 검증
def verify_registration(user_id: str, credential: dict):
    expected_challenge = redis_client.get(f"webauthn:register:{user_id}")

    verification = verify_registration_response(
        credential=credential,
        expected_challenge=expected_challenge,
        expected_rp_id=RP_ID,
        expected_origin=ORIGIN,
        require_user_verification=True
    )

    # DB에 크레덴셜 저장
    db.credentials.insert_one({
        "user_id": user_id,
        "credential_id": verification.credential_id,
        "public_key": verification.credential_public_key,
        "sign_count": verification.sign_count,
        "created_at": datetime.utcnow()
    })

    return {"success": True, "credential_id": verification.credential_id.hex()}

# 인증 옵션 생성
def create_authentication_options(user_id: str = None):
    # 사용자의 등록된 크레덴셜 조회
    allow_credentials = []
    if user_id:
        creds = db.credentials.find({"user_id": user_id})
        allow_credentials = [
            PublicKeyCredentialDescriptor(id=c["credential_id"])
            for c in creds
        ]

    options = generate_authentication_options(
        rp_id=RP_ID,
        user_verification=UserVerificationRequirement.REQUIRED,
        allow_credentials=allow_credentials
    )

    redis_client.setex("webauthn:auth:challenge", 300, options.challenge)
    return options_to_json(options)

# 인증 응답 검증
def verify_authentication(credential: dict):
    expected_challenge = redis_client.get("webauthn:auth:challenge")
    stored_cred = db.credentials.find_one({
        "credential_id": bytes.fromhex(credential["id"])
    })

    verification = verify_authentication_response(
        credential=credential,
        expected_challenge=expected_challenge,
        expected_rp_id=RP_ID,
        expected_origin=ORIGIN,
        credential_public_key=stored_cred["public_key"],
        credential_current_sign_count=stored_cred["sign_count"],
        require_user_verification=True
    )

    # 서명 카운터 업데이트
    db.credentials.update_one(
        {"_id": stored_cred["_id"]},
        {"$set": {"sign_count": verification.new_sign_count}}
    )

    return {
        "success": True,
        "user_id": stored_cred["user_id"]
    }

🗣️ Say It Like This in Practice

💬 In a discussion on improving the authentication system
"Password leaks keep happening, so let's introduce passkey login with WebAuthn. Users just touch once with Face ID or Touch ID, and only the public key is stored on the server, so a leak isn't a problem. Phishing is blocked at the source, too."
💬 In an MLOps security meeting
"We need to apply WebAuthn MFA to access to the model training pipeline. Attacks that steal passwords with automated scripts are increasing, but WebAuthn backed by a hardware authenticator can't be broken without physical access."
💬 When collaborating with the UX team
"WebAuthn passkeys have much better UX than passwords. Users don't need to remember complicated passwords; a single biometric check is all it takes. Both sign-up conversion and login success rates should go up."

⚠️ Cautions & Best Practices

❌
Forcing WebAuthn only, with no password fallback

Not all browsers and devices support WebAuthn yet. Start with password + WebAuthn MFA as an option at first, then gradually move to passkey-only. An account recovery plan is also essential.

❌
Reusing challenges or skipping verification

Generate a new challenge for every request and manage it with a short TTL. To prevent replay attacks, always check and update the signature counter. If the counter decreases, suspect a cloning attack.

❌
rpId misconfiguration

The rpId is bound to the domain; a subdomain can use its parent domain's rpId, but not the other way around. In a multi-site environment, plan your rpId strategy carefully.

✅
WebAuthn best practices

Support passkeys with residentKey: required, and enforce biometric verification with userVerification: required. Set attestation to none to protect privacy, and allow registering multiple authenticators to prepare for a lost device.

🔗 Related Terms

📚 Learn More