Integrasikan Cap Jari dan Pengesahan ID Wajah dalam Apl Sudut Anda Menggunakan WebAuthn: Panduan Langkah demi Langkah

王林
Lepaskan: 2024-09-05 19:00:21
asal
657 orang telah melayarinya

솔직히 말하자면, 우리 모두는 모바일 앱에서처럼 지문이나 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
Salin selepas log masuk

이것은 기본 Angular 애플리케이션을 설정하고 ngserv를 실행하면 http://localhost:4200/에서 앱이 시작됩니다. 기본 Angular 시작 페이지가 표시됩니다. 이제 생체 인증을 위해 WebAuthn을 통합할 준비가 되었습니다.

2단계: WebAuthn 서비스 생성

생체인식을 사용한 등록 및 인증을 포함하여 모든 WebAuthn 기능을 관리하려면 Angular의 서비스가 필요합니다. 다음을 실행하여 이 서비스를 만들어 보겠습니다.

ng generate service services/webauthn
Salin selepas log masuk

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
  }
}
Salin selepas log masuk

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;
    }
  }
}
Salin selepas log masuk

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:

    • Pelanggan menghantar semula objek PublicKeyCredentialRequestOptions yang mengandungi respons kepada cabaran.
    • Halaman belakang menyahkod dan mengesahkan respons ini, memastikan cabaran dan bukti kelayakan sepadan dengan apa yang disimpan dalam pangkalan data.
  • Pengesahan Bukti kelayakan:

    • Kunci awam yang disimpan semasa pendaftaran digunakan untuk mengesahkan tandatangan dalam respons log masuk.
    • Jika bukti kelayakan sepadan, bahagian belakang membenarkan log masuk dan menjana token pengesahan (seperti JWT) untuk sesi.

Pengendalian Ralat:

  • 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.

Pertimbangan Keselamatan

  • 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.

Secara ringkasnya

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!

sumber:dev.to
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!