솔직히 말하자면, 우리 모두는 모바일 앱에서처럼 지문이나 Face ID를 사용하여 웹사이트에 로그인할 수 있기를 바랐습니다. 그렇죠? 음, 웹 생체 인식 덕분에 그 꿈은 더 이상 그리 멀지 않습니다. 길고 복잡한 비밀번호를 버리고 단순히 지문이나 얼굴을 사용하여 즐겨찾는 웹사이트에 로그인한다고 상상해 보세요. 정말 멋지지 않나요?
WebAuthn을 기반으로 하는 웹 생체인식 기술이 이를 가능하게 합니다. 이는 휴대폰의 지문 센서나 안면 인식과 동일한 종류의 보안을 사용하여 웹 브라우저에서 직접 인증하는 매우 간단한 기능에 대한 멋진 이름입니다. 더 이상 비밀번호 유출이나 도난에 대해 걱정하지 마세요. 간단히 스캔만 하면 됩니다.
이 튜토리얼에서는 지문과 Face ID 로그인을 Angular 앱에 통합하는 방법을 직접 살펴보겠습니다. WebAuthn API의 작동 방식과 모든 것을 안전하고 원활하게 유지하기 위해 백엔드에서 수행해야 하는 작업과 같은 필수 사항을 다루겠습니다. 생각보다 쉽습니다. 마지막에는 인증의 미래를 위해 앱을 모두 설정하게 됩니다. 이제 본격적으로 로그인을 시작해 보세요!
자, 코드를 시작하기 전에 WebAuthn이 무엇인지 빠르게 살펴보겠습니다. WebAuthn을 지문이나 Face ID와 같이 휴대폰에서 즐겨 사용하는 멋진 생체 인식 기능을 브라우저에서 바로 앱에 연결하는 다리라고 생각하세요. 공개 키 암호화를 사용하여 사용자를 인증합니다. 즉, 해커가 쉽게 알아낼 수 있는 일반 비밀번호를 더 이상 저장할 필요가 없습니다. 대신에 우리는 로그인을 안전하고 원활하게 만들어주는 안전하게 생성된 키에 대해 이야기하고 있습니다.
작업을 진행하려면 WebAuthn 게임의 주요 플레이어인 PublicKeyCredentialCreationOptions 및 PublicKeyCredentialRequestOptions를 이해해야 합니다. 긴 이름 때문에 겁먹지 마세요. 이름은 브라우저에 사용자 등록 및 인증 방법을 알려주는 멋진 방법일 뿐입니다.
새 사용자 자격 증명을 설정할 때 사용하는 개체입니다. 여기에는 다음이 포함됩니다.
사용자를 확인할 때가 되면 이 개체가 주목을 받습니다. 여기에는 다음이 포함됩니다.
이러한 개체를 사용하면 Angular 앱이 사용자에게 생체 인식 데이터를 등록하고 빠르고 안전하게 인증하도록 안내할 수 있습니다. 다음으로, 코드를 작성하여 앱에서 이 마법이 어떻게 일어나는지 살펴보겠습니다!
이 섹션에서는 WebAuthn을 사용한 생체 인식 인증으로 Angular 애플리케이션을 설정하는 과정을 안내합니다. 지문과 Face ID 활용에 집중할 테니 손을 더럽히자!
시작하려면 새 Angular 프로젝트를 만들어 보겠습니다. 터미널을 열고 다음 명령을 입력하세요:
ng new web-biometrics-demo cd web-biometrics-demo ng serve
이것은 기본 Angular 애플리케이션을 설정하고 ngserv를 실행하면 http://localhost:4200/에서 앱이 시작됩니다. 기본 Angular 시작 페이지가 표시됩니다. 이제 생체 인증을 위해 WebAuthn을 통합할 준비가 되었습니다.
생체인식을 사용한 등록 및 인증을 포함하여 모든 WebAuthn 기능을 관리하려면 Angular의 서비스가 필요합니다. 다음을 실행하여 이 서비스를 만들어 보겠습니다.
ng generate service services/webauthn
Now, open webauthn.service.ts and add the following code:
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class WebAuthnService { constructor() { } // Generates a random buffer to use as a challenge, which is a unique value needed for security private generateRandomBuffer(length: number): Uint8Array { const randomBuffer = new Uint8Array(length); window.crypto.getRandomValues(randomBuffer); // Fills the buffer with cryptographically secure random values return randomBuffer; } // Registers a new credential (like a fingerprint or Face ID) for the user async register() { // Generate a unique challenge for the registration process const challenge = this.generateRandomBuffer(32); // PublicKeyCredentialCreationOptions is the core object needed for registration const publicKey: PublicKeyCredentialCreationOptions = { challenge: challenge, // A random value generated by the server to ensure the request is fresh and unique rp: { // Relying Party (your app) information name: "OurAwesomeApp" // Display name of your app }, user: { // User information id: this.generateRandomBuffer(16), // A unique identifier for the user name: "user@example.com", // User's email or username displayName: "User Example" // A friendly name for the user }, pubKeyCredParams: [{ // Array of acceptable public key algorithms type: "public-key", alg: -7 // Represents the ES256 algorithm (Elliptic Curve Digital Signature Algorithm) }], authenticatorSelection: { // Criteria for selecting the appropriate authenticator authenticatorAttachment: "platform", // Ensures we use the device's built-in biometric authenticator like Touch ID or Face ID userVerification: "required" // Requires user verification (e.g., fingerprint or face scan) }, timeout: 60000, // Timeout for the registration operation in milliseconds attestation: "direct" // Attestation provides proof of the authenticator's properties and is sent back to the server }; try { // This will prompt the user to register their biometric credential const credential = await navigator.credentials.create({ publicKey }) as PublicKeyCredential; this.storeCredential(credential, challenge); // Store the credential details locally for demo purposes console.log("Registration successful!", credential); return credential; // Return the credential object containing the user's public key and other details } catch (err) { console.error("Registration failed:", err); throw err; // Handle any errors that occur during registration } } // Authenticates the user with stored credentials (like a fingerprint or Face ID) async authenticate() { const storedCredential = this.getStoredCredential(); // Retrieve stored credential information if (!storedCredential) { throw new Error("No stored credential found. Please register first."); // Error if no credentials are found } // PublicKeyCredentialRequestOptions is used to prompt the user to authenticate const publicKey: PublicKeyCredentialRequestOptions = { challenge: new Uint8Array(storedCredential.challenge), // A new challenge to ensure the request is fresh and unique allowCredentials: [{ // Specifies which credentials can be used for authentication id: new Uint8Array(storedCredential.rawId), // The ID of the credential to use type: "public-key" }], userVerification: "required", // Requires user verification (e.g., fingerprint or face scan) timeout: 60000 // Timeout for the authentication operation in milliseconds }; try { // This will prompt the user to authenticate using their registered biometric credential const credential = await navigator.credentials.get({ publicKey }) as PublicKeyCredential; console.log("Authentication successful!", credential); return credential; // Return the credential object with authentication details } catch (err) { console.error("Authentication failed:", err); throw err; // Handle any errors that occur during authentication } } // Stores credential data in localStorage (for demo purposes only; this should be handled securely in production) private storeCredential(credential: PublicKeyCredential, challenge: Uint8Array) { const credentialData = { rawId: Array.from(new Uint8Array(credential.rawId)), // Converts the raw ID to an array for storage challenge: Array.from(challenge) // Converts the challenge to an array for storage }; localStorage.setItem('webauthn_credential', JSON.stringify(credentialData)); // Store the data as a JSON string } // Retrieves stored credential data from localStorage private getStoredCredential(): any { const storedCredential = localStorage.getItem('webauthn_credential'); return storedCredential ? JSON.parse(storedCredential) : null; // Parse the stored JSON back into an object } }
generateRandomBuffer: Creates a random buffer that serves as a challenge to ensure each authentication or registration request is unique.
register: This method sets up the biometric registration process. It uses PublicKeyCredentialCreationOptions to define parameters like the challenge, relying party (your app), user information, and acceptable public key algorithms. When navigator.credentials.create() is called, the browser prompts the user to register their biometric data.
authenticate: This method handles user authentication with biometrics. It uses PublicKeyCredentialRequestOptions to define the authentication challenge and credentials that can be used. The method prompts the user to authenticate with their registered biometrics.
storeCredential and getStoredCredential: These methods handle storing and retrieving credentials in localStorage for demonstration purposes.
In a real-world app, you’d securely store this information on your backend.
Now, let’s create a basic UI with buttons to trigger the registration and login functions. This UI will provide feedback based on whether the registration or login was successful.
Open app.component.ts and replace the content with the following:
import { Component } from '@angular/core'; import { WebAuthnService } from './services/webauthn.service'; @Component({ selector: 'app-root', template: ` <div class="auth-container"> <h1>Web Biometrics in Angular</h1> <button (click)="register()">Register with Fingerprint</button> <button (click)="login()">Login with Face ID</button> <p *ngIf="message" [ngClass]="{'success': isSuccess, 'error': !isSuccess}">{{ message }}</p> </div> `, styles: [` .auth-container { text-align: center; padding: 50px; } .success { color: green; } .error { color: red; } button { margin: 10px; padding: 10px 20px; font-size: 16px; } p { margin: 10px; font-size: 16px; } `] }) export class AppComponent { message: string | null = null; // Message to display feedback to the user isSuccess: boolean = false; // Indicates if the last action was successful constructor(private webAuthnService: WebAuthnService) { } // Trigger registration process and update the UI based on the outcome async register() { try { await this.webAuthnService.register(); this.message = "Registration successful!"; // Success message if registration works this.isSuccess = true; } catch (err) { this.message = "Registration failed. Please try again."; // Error message if something goes wrong this.isSuccess = false; } } // Trigger authentication process and update the UI based on the outcome async login() { try { await this.webAuthnService.authenticate(); this.message = "Authentication successful!"; // Success message if authentication works this.isSuccess = true; } catch (err) { this.message = "Authentication failed. Please try again."; // Error message if something goes wrong this.isSuccess = false; } } }
register and login methods: These methods call the respective register and authenticate methods from the WebAuthnService. If successful, a success message is displayed; otherwise, an error message is shown.
Template and Styling: The template includes buttons to trigger registration and login, and it displays messages to the user based on the operation's outcome. The buttons are styled for simplicity.
That’s it! We’ve built a basic Angular app with WebAuthn-based biometric authentication, supporting fingerprints and Face ID. This setup captures the core concepts and lays a foundation that can be expanded with additional features and security measures for a production environment.
When implementing biometric authentication like fingerprints or Face ID in web applications using WebAuthn, the backend plays a crucial role in managing the security and flow of data. Here’s a breakdown of how the backend processes work in theory, focusing on registration and login functionalities.
User Data Capture: During registration, the user provides basic credentials, such as an email and password. If biometric data is also being registered, this is captured as part of the WebAuthn response.
Password Hashing: For security, passwords are never stored in plain text. Instead, they are hashed using a library like bcrypt before being stored in the database.
Storing WebAuthn Credentials:
The backend uses libraries like cbor to decode binary data formats from the WebAuthn response, extracting necessary elements like the public key and authenticator data.
It ensures that the challenge from the initial registration request matches what is returned in the WebAuthn response to verify the authenticity of the registration.
If the WebAuthn response passes all checks, the credentials are saved in the database, linked to the user account.
Challenge Generation: Similar to registration, the server generates a challenge that must be responded to by the client’s authenticator during login.
Validating the WebAuthn Response:
Pengesahan Bukti kelayakan:
Tidak Padan atau Respons Tidak Sah: Jika respons cabaran tidak sepadan dengan nilai yang dijangkakan atau jika bukti kelayakan WebAuthn tidak mengesahkan dengan betul, bahagian belakang bertindak balas dengan ralat, menghalang akses tanpa kebenaran.
Saling Balik kepada Kata Laluan: Jika WebAuthn gagal atau tidak tersedia, sistem boleh kembali kepada pengesahan kata laluan tradisional, memastikan pengguna masih boleh mengakses akaun mereka.
Integriti Data: Integriti bukti kelayakan WebAuthn adalah kritikal. Sebarang pengubahsuaian dalam storan atau penghantaran akan menyebabkan pengesahan gagal, sekali gus menjamin proses pengesahan.
Cabaran Nonces: Penggunaan cabaran yang unik dan terhad masa memastikan bahawa respons tidak boleh digunakan semula, melindungi daripada serangan ulangan.
Storan Kunci Awam: Menyimpan kunci awam sahaja (yang tidak boleh digunakan untuk menyamar sebagai pengguna) meningkatkan keselamatan, kerana kunci peribadi kekal pada peranti klien.
Dengan mengikut prinsip ini, bahagian belakang mengurus pengesahan biometrik dengan berkesan, memastikan pengalaman yang selamat dan lancar untuk pengguna yang ingin menggunakan ciri seperti cap jari atau Face ID dalam apl Sudut mereka.
Dalam tutorial ini, kami masuk ke dalam menyepadukan pengesahan biometrik dengan Angular menggunakan WebAuthn. Kami merangkumi perkara penting, daripada memahami objek WebAuthn utama seperti PublicKeyCredentialCreationOptions dan PublicKeyCredentialRequestOptions kepada menyediakan perkhidmatan Angular dan komponen UI untuk proses pendaftaran dan log masuk yang lancar. Kami juga membincangkan pertimbangan bahagian belakang yang diperlukan untuk mengendalikan pengesahan biometrik dengan selamat.
Bagi mereka yang ingin melihat WebAuthn sedang beraksi, saya telah menyediakan demo dan repositori dengan pelaksanaan yang lengkap. Anda boleh menyemak demo di sini dan meneroka kod sumber di GitHub di repositori ini.
Merangkul pengesahan biometrik bukan sahaja meningkatkan keselamatan tetapi juga memudahkan pengalaman pengguna, membuka jalan untuk masa depan di mana log masuk semudah imbasan cap jari atau pengecaman muka pantas. Apabila anda menyepadukan ciri ini ke dalam apl Angular anda, anda akan menyumbang kepada web yang lebih selamat dan mesra pengguna. Selamat mengekod!
Atas ialah kandungan terperinci Integrasikan Cap Jari dan Pengesahan ID Wajah dalam Apl Sudut Anda Menggunakan WebAuthn: Panduan Langkah demi Langkah. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!