WebAuthn을 사용하여 Angular 앱에 지문 및 얼굴 ID 인증 통합: 단계별 가이드
솔직히 말하자면, 우리 모두는 모바일 앱에서처럼 지문이나 Face ID를 사용하여 웹사이트에 로그인할 수 있기를 바랐습니다. 그렇죠? 음, 웹 생체 인식 덕분에 그 꿈은 더 이상 그리 멀지 않습니다. 길고 복잡한 비밀번호를 버리고 단순히 지문이나 얼굴을 사용하여 즐겨찾는 웹사이트에 로그인한다고 상상해 보세요. 정말 멋지지 않나요?
WebAuthn을 기반으로 하는 웹 생체인식 기술이 이를 가능하게 합니다. 이는 휴대폰의 지문 센서나 안면 인식과 동일한 종류의 보안을 사용하여 웹 브라우저에서 직접 인증하는 매우 간단한 기능에 대한 화려한 이름입니다. 더 이상 비밀번호 유출이나 도난에 대해 걱정하지 마세요. 간단히 스캔만 하면 됩니다.
이 튜토리얼에서는 지문과 Face ID 로그인을 Angular 앱에 통합하는 방법을 직접 살펴보겠습니다. WebAuthn API의 작동 방식과 모든 것을 안전하고 원활하게 유지하기 위해 백엔드에서 수행해야 하는 작업과 같은 필수 사항을 다루겠습니다. 생각보다 쉽습니다. 마지막에는 인증의 미래를 위해 앱을 모두 설정하게 됩니다. 이제 본격적으로 로그인을 시작해 보세요!
WebAuthn 이해: Angular 앱의 지문 및 얼굴 인식에 대한 기본 사항
자, 코드를 시작하기 전에 WebAuthn이 무엇인지 빠르게 살펴보겠습니다. WebAuthn을 지문이나 Face ID와 같이 휴대폰에서 즐겨 사용하는 멋진 생체 인식 기능을 브라우저에서 바로 앱에 연결하는 다리라고 생각하세요. 공개 키 암호화를 사용하여 사용자를 인증합니다. 즉, 해커가 쉽게 알아낼 수 있는 일반 비밀번호를 더 이상 저장할 필요가 없습니다. 대신에 우리는 로그인을 안전하고 원활하게 만들어주는 안전하게 생성된 키에 대해 이야기하고 있습니다.
주요 개체 및 역할
작업을 진행하려면 WebAuthn 게임의 주요 플레이어인 PublicKeyCredentialCreationOptions 및 PublicKeyCredentialRequestOptions를 이해해야 합니다. 긴 이름 때문에 겁먹지 마세요. 이름은 브라우저에 사용자 등록 및 인증 방법을 알려주는 멋진 방법일 뿐입니다.
1. PublicKeyCredentialCreationOptions
새 사용자 자격 증명을 설정할 때 사용하는 개체입니다. 여기에는 다음이 포함됩니다.
- 챌린지: 응답이 최신이고 재사용할 수 없도록 서버에서 생성된 고유한 임의 값입니다.
- rp: Relying Party(당사의 앱)를 의미하며 앱 이름 및 ID와 같은 세부정보가 포함됩니다.
- 사용자: 고유 ID, 사용자 이름, 표시 이름 등 사용자에 대한 정보입니다.
- pubKeyCredParams: 허용되는 공개 키 알고리즘 목록입니다.
- authenticatorSelection: 첨부 파일 유형(플랫폼 또는 크로스 플랫폼) 및 사용자 확인 수준 등을 기반으로 올바른 유형의 인증자를 선택하는 데 도움이 됩니다.
2. PublicKeyCredentialRequestOptions
사용자를 확인할 때가 되면 이 개체가 주목을 받습니다. 여기에는 다음이 포함됩니다.
- 도전: 이전과 마찬가지로 인증 요청이 신선하고 고유하다는 것을 보장합니다.
- allowCredentials: 사용자에게 허용되는 자격 증명을 지정합니다.
- userVerification: 사용자 확인(예: 지문 스캔)이 필요한지 여부를 나타냅니다.
이러한 개체를 사용하면 Angular 앱이 사용자에게 생체 인식 데이터를 등록하고 빠르고 안전하게 인증하도록 안내할 수 있습니다. 다음으로, 코드를 살펴보고 앱에서 이 마법이 어떻게 일어나는지 살펴보겠습니다!
Angular 앱 설정
이 섹션에서는 WebAuthn을 사용한 생체 인식 인증으로 Angular 애플리케이션을 설정하는 과정을 안내합니다. 지문과 Face ID 활용에 집중할 테니 손을 더럽히자!
1단계: Angular 프로젝트 설정
시작하려면 새 Angular 프로젝트를 만들어 보겠습니다. 터미널을 열고 다음 명령을 입력하세요:
ng new web-biometrics-demo cd web-biometrics-demo ng serve
이것은 기본 Angular 애플리케이션을 설정하고 ngserv를 실행하면 http://localhost:4200/에서 앱이 시작됩니다. 기본 Angular 시작 페이지가 표시됩니다. 이제 생체 인증을 위해 WebAuthn을 통합할 준비가 되었습니다.
2단계: 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 } }
What’s Happening in the Code?
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.
Step 3: Building the UI
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; } } }
What’s Happening in the Component?
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.
Backend Considerations
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.
Registration: Sign-up
1. User Registration Flow:
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:
- Challenge Handling: The server sends a challenge during the registration process, which is a randomly generated value to prevent replay attacks.
- Response Validation: When the client responds with the WebAuthn data, it includes clientDataJSON and attestationObject that need to be decoded and verified.
- Credential Storage: After validation, key data from the response—like the webauthnId (a unique identifier for the credential) and the publicKey (used to verify future authentications)—are stored in the database alongside the user record.
2. Backend Code Responsibilities:
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.
Login
1. User Login Flow:
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:
- Le client renvoie un objet PublicKeyCredentialRequestOptions contenant la réponse au défi.
- Le backend décode et vérifie cette réponse, s'assurant que le défi et les informations d'identification correspondent à ce qui est stocké dans la base de données.
-
Vérification des informations d'identification :
- La clé publique stockée lors de l'inscription est utilisée pour vérifier la signature dans la réponse de connexion.
- Si les informations d'identification correspondent, le backend autorise la connexion et génère un jeton d'authentification (comme un JWT) pour la session.
Gestion des erreurs :
Incompatibilité ou réponse invalide : si la réponse au défi ne correspond pas aux valeurs attendues, ou si les informations d'identification WebAuthn ne sont pas vérifiées correctement, le backend répond avec une erreur, empêchant tout accès non autorisé.
Retour au mot de passe : si WebAuthn échoue ou n'est pas disponible, le système peut revenir à la vérification traditionnelle du mot de passe, garantissant que les utilisateurs peuvent toujours accéder à leurs comptes.
Considérations de sécurité
Intégrité des données : L'intégrité des informations d'identification WebAuthn est essentielle. Toute modification de stockage ou de transmission entraînerait l'échec de la vérification, sécurisant ainsi le processus d'authentification.
Challenge Nonces : L'utilisation de défis uniques et limités dans le temps garantit que les réponses ne peuvent pas être réutilisées, protégeant ainsi contre les attaques par relecture.
Stockage des clés publiques : le stockage uniquement des clés publiques (qui ne peuvent pas être utilisées pour usurper l'identité de l'utilisateur) améliore la sécurité, car les clés privées restent sur l'appareil client.
En suivant ces principes, le backend gère efficacement l'authentification biométrique, garantissant une expérience sécurisée et transparente aux utilisateurs souhaitant utiliser des fonctionnalités telles que les empreintes digitales ou Face ID dans leurs applications Angular.
En résumé
Dans ce tutoriel, nous avons abordé l'intégration de l'authentification biométrique avec Angular à l'aide de WebAuthn. Nous avons couvert l'essentiel, depuis la compréhension des objets WebAuthn clés tels que PublicKeyCredentialCreationOptions et PublicKeyCredentialRequestOptions jusqu'à la configuration des services Angular et des composants d'interface utilisateur pour un processus d'enregistrement et de connexion fluide. Nous avons également discuté des considérations backend nécessaires pour gérer en toute sécurité l'authentification biométrique.
Pour ceux qui souhaitent voir WebAuthn en action, j'ai fourni une démo et un référentiel avec une implémentation complète. Vous pouvez consulter la démo ici et explorer le code source sur GitHub dans ce référentiel.
L'adoption de l'authentification biométrique améliore non seulement la sécurité, mais simplifie également l'expérience utilisateur, ouvrant la voie à un avenir où la connexion est aussi simple qu'une numérisation d'empreintes digitales ou une reconnaissance faciale rapide. En intégrant ces fonctionnalités dans vos applications Angular, vous contribuerez à un Web plus sécurisé et plus convivial. Bon codage !
위 내용은 WebAuthn을 사용하여 Angular 앱에 지문 및 얼굴 ID 인증 통합: 단계별 가이드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

JavaScript의 최신 트렌드에는 Typescript의 Rise, 현대 프레임 워크 및 라이브러리의 인기 및 WebAssembly의 적용이 포함됩니다. 향후 전망은보다 강력한 유형 시스템, 서버 측 JavaScript 개발, 인공 지능 및 기계 학습의 확장, IoT 및 Edge 컴퓨팅의 잠재력을 포함합니다.

각각의 엔진의 구현 원리 및 최적화 전략이 다르기 때문에 JavaScript 엔진은 JavaScript 코드를 구문 분석하고 실행할 때 다른 영향을 미칩니다. 1. 어휘 분석 : 소스 코드를 어휘 단위로 변환합니다. 2. 문법 분석 : 추상 구문 트리를 생성합니다. 3. 최적화 및 컴파일 : JIT 컴파일러를 통해 기계 코드를 생성합니다. 4. 실행 : 기계 코드를 실행하십시오. V8 엔진은 즉각적인 컴파일 및 숨겨진 클래스를 통해 최적화하여 Spidermonkey는 유형 추론 시스템을 사용하여 동일한 코드에서 성능이 다른 성능을 제공합니다.

Python은 부드러운 학습 곡선과 간결한 구문으로 초보자에게 더 적합합니다. JavaScript는 가파른 학습 곡선과 유연한 구문으로 프론트 엔드 개발에 적합합니다. 1. Python Syntax는 직관적이며 데이터 과학 및 백엔드 개발에 적합합니다. 2. JavaScript는 유연하며 프론트 엔드 및 서버 측 프로그래밍에서 널리 사용됩니다.

JavaScript는 현대 웹 개발의 핵심 언어이며 다양성과 유연성에 널리 사용됩니다. 1) 프론트 엔드 개발 : DOM 운영 및 최신 프레임 워크 (예 : React, Vue.js, Angular)를 통해 동적 웹 페이지 및 단일 페이지 응용 프로그램을 구축합니다. 2) 서버 측 개발 : Node.js는 비 차단 I/O 모델을 사용하여 높은 동시성 및 실시간 응용 프로그램을 처리합니다. 3) 모바일 및 데스크탑 애플리케이션 개발 : 크로스 플랫폼 개발은 개발 효율을 향상시키기 위해 반응 및 전자를 통해 실현됩니다.

이 기사에서는 Contrim에 의해 확보 된 백엔드와의 프론트 엔드 통합을 보여 주며 Next.js를 사용하여 기능적인 Edtech SaaS 응용 프로그램을 구축합니다. Frontend는 UI 가시성을 제어하기 위해 사용자 권한을 가져오고 API가 역할 기반을 준수하도록합니다.

일상적인 기술 도구를 사용하여 기능적 다중 테넌트 SaaS 응용 프로그램 (Edtech 앱)을 구축했으며 동일한 작업을 수행 할 수 있습니다. 먼저, 다중 테넌트 SaaS 응용 프로그램은 무엇입니까? 멀티 테넌트 SAAS 응용 프로그램은 노래에서 여러 고객에게 서비스를 제공 할 수 있습니다.

C/C에서 JavaScript로 전환하려면 동적 타이핑, 쓰레기 수집 및 비동기 프로그래밍으로 적응해야합니다. 1) C/C는 수동 메모리 관리가 필요한 정적으로 입력 한 언어이며 JavaScript는 동적으로 입력하고 쓰레기 수집이 자동으로 처리됩니다. 2) C/C를 기계 코드로 컴파일 해야하는 반면 JavaScript는 해석 된 언어입니다. 3) JavaScript는 폐쇄, 프로토 타입 체인 및 약속과 같은 개념을 소개하여 유연성과 비동기 프로그래밍 기능을 향상시킵니다.

웹 개발에서 JavaScript의 주요 용도에는 클라이언트 상호 작용, 양식 검증 및 비동기 통신이 포함됩니다. 1) DOM 운영을 통한 동적 컨텐츠 업데이트 및 사용자 상호 작용; 2) 사용자가 사용자 경험을 향상시키기 위해 데이터를 제출하기 전에 클라이언트 확인이 수행됩니다. 3) 서버와의 진실한 통신은 Ajax 기술을 통해 달성됩니다.
