WebAuthn을 사용하여 Angular 앱에 지문 및 얼굴 ID 인증 통합: 단계별 가이드

王林
풀어 주다: 2024-09-05 19:00:21
원래의
657명이 탐색했습니다.

솔직히 말하자면, 우리 모두는 모바일 앱에서처럼 지문이나 Face ID를 사용하여 웹사이트에 로그인할 수 있기를 바랐습니다. 그렇죠? 음, 웹 생체 인식 덕분에 그 꿈은 더 이상 그리 멀지 않습니다. 길고 복잡한 비밀번호를 버리고 단순히 지문이나 얼굴을 사용하여 즐겨찾는 웹사이트에 로그인한다고 상상해 보세요. 정말 멋지지 않나요?

Integrate Fingerprint and Face ID Authentication in Your Angular App Using WebAuthn: A Step-by-Step Guide

WebAuthn을 기반으로 하는 웹 생체인식 기술이 이를 가능하게 합니다. 이는 휴대폰의 지문 센서나 안면 인식과 동일한 종류의 보안을 사용하여 웹 브라우저에서 직접 인증하는 매우 간단한 기능에 대한 화려한 이름입니다. 더 이상 비밀번호 유출이나 도난에 대해 걱정하지 마세요. 간단히 스캔만 하면 됩니다.

이 튜토리얼에서는 지문과 Face ID 로그인을 Angular 앱에 통합하는 방법을 직접 살펴보겠습니다. WebAuthn API의 작동 방식과 모든 것을 안전하고 원활하게 유지하기 위해 백엔드에서 수행해야 하는 작업과 같은 필수 사항을 다루겠습니다. 생각보다 쉽습니다. 마지막에는 인증의 미래를 위해 앱을 모두 설정하게 됩니다. 이제 본격적으로 로그인을 시작해 보세요!

WebAuthn 이해: Angular 앱의 지문 및 얼굴 인식에 대한 기본 사항

Integrate Fingerprint and Face ID Authentication in Your Angular App Using WebAuthn: A Step-by-Step Guide

자, 코드를 시작하기 전에 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!