솔직히 말하자면, 우리 모두는 모바일 앱에서처럼 지문이나 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 id="Web-Biometrics-in-Angular">Web Biometrics in Angular</h1> <button>Register with Fingerprint</button> <button>Login with Face ID</button> <p 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

Python과 JavaScript의 주요 차이점은 유형 시스템 및 응용 프로그램 시나리오입니다. 1. Python은 과학 컴퓨팅 및 데이터 분석에 적합한 동적 유형을 사용합니다. 2. JavaScript는 약한 유형을 채택하며 프론트 엔드 및 풀 스택 개발에 널리 사용됩니다. 두 사람은 비동기 프로그래밍 및 성능 최적화에서 고유 한 장점을 가지고 있으며 선택할 때 프로젝트 요구 사항에 따라 결정해야합니다.

Python 또는 JavaScript를 선택할지 여부는 프로젝트 유형에 따라 다릅니다. 1) 데이터 과학 및 자동화 작업을 위해 Python을 선택하십시오. 2) 프론트 엔드 및 풀 스택 개발을 위해 JavaScript를 선택하십시오. Python은 데이터 처리 및 자동화 분야에서 강력한 라이브러리에 선호되는 반면 JavaScript는 웹 상호 작용 및 전체 스택 개발의 장점에 없어서는 안될 필수입니다.

파이썬과 자바 스크립트는 각각 고유 한 장점이 있으며 선택은 프로젝트 요구와 개인 선호도에 따라 다릅니다. 1. Python은 간결한 구문으로 데이터 과학 및 백엔드 개발에 적합하지만 실행 속도가 느립니다. 2. JavaScript는 프론트 엔드 개발의 모든 곳에 있으며 강력한 비동기 프로그래밍 기능을 가지고 있습니다. node.js는 풀 스택 개발에 적합하지만 구문은 복잡하고 오류가 발생할 수 있습니다.

javaScriptisNotBuiltoncorc; it'SangretedLanguageThatrunsonOngineStenWrittenInc .1) javaScriptWasDesignEdasAlightweight, 해석 hanguageforwebbrowsers.2) Endinesevolvedfromsimpleplemporectreterstoccilpilers, 전기적으로 개선된다.

JavaScript는 프론트 엔드 및 백엔드 개발에 사용할 수 있습니다. 프론트 엔드는 DOM 작업을 통해 사용자 경험을 향상시키고 백엔드는 Node.js를 통해 서버 작업을 처리합니다. 1. 프론트 엔드 예 : 웹 페이지 텍스트의 내용을 변경하십시오. 2. 백엔드 예제 : node.js 서버를 만듭니다.

Python 또는 JavaScript는 경력 개발, 학습 곡선 및 생태계를 기반으로해야합니다. 1) 경력 개발 : Python은 데이터 과학 및 백엔드 개발에 적합한 반면 JavaScript는 프론트 엔드 및 풀 스택 개발에 적합합니다. 2) 학습 곡선 : Python 구문은 간결하며 초보자에게 적합합니다. JavaScript Syntax는 유연합니다. 3) 생태계 : Python에는 풍부한 과학 컴퓨팅 라이브러리가 있으며 JavaScript는 강력한 프론트 엔드 프레임 워크를 가지고 있습니다.

JavaScript 프레임 워크의 힘은 개발 단순화, 사용자 경험 및 응용 프로그램 성능을 향상시키는 데 있습니다. 프레임 워크를 선택할 때 : 1. 프로젝트 규모와 복잡성, 2. 팀 경험, 3. 생태계 및 커뮤니티 지원.

서론 나는 당신이 이상하다는 것을 알고 있습니다. JavaScript, C 및 Browser는 정확히 무엇을해야합니까? 그들은 관련이없는 것처럼 보이지만 실제로는 현대 웹 개발에서 매우 중요한 역할을합니다. 오늘 우리는이 세 가지 사이의 밀접한 관계에 대해 논의 할 것입니다. 이 기사를 통해 브라우저에서 JavaScript가 어떻게 실행되는지, 브라우저 엔진의 C 역할 및 웹 페이지의 렌더링 및 상호 작용을 유도하기 위해 함께 작동하는 방법을 알게됩니다. 우리는 모두 JavaScript와 브라우저의 관계를 알고 있습니다. JavaScript는 프론트 엔드 개발의 핵심 언어입니다. 브라우저에서 직접 실행되므로 웹 페이지를 생생하고 흥미롭게 만듭니다. 왜 Javascr


핫 AI 도구

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

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

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

Clothoff.io
AI 옷 제거제

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

인기 기사

뜨거운 도구

VSCode Windows 64비트 다운로드
Microsoft에서 출시한 강력한 무료 IDE 편집기

Dreamweaver Mac版
시각적 웹 개발 도구

mPDF
mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

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

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