首頁  >  文章  >  web前端  >  教學:如何將金鑰整合到 Angular 中

教學:如何將金鑰整合到 Angular 中

王林
王林原創
2024-08-28 06:10:361014瀏覽

Tutorial: How to Integrate Passkeys into Angular

使用 TypeScript 在 Angular 中實作金鑰驗證

在本指南中,我們將逐步介紹使用 TypeScript 將金鑰驗證整合到 Angular 應用程式中的過程。金鑰提供了一種安全且可擴展的方式來管理使用者身份驗證,無需傳統密碼。

在我們的原始部落格文章中查看完整教學

先決條件

開始之前,請確保您熟悉 Angular、HTML、CSS 和 TypeScript。此外,請確保您的電腦上安裝了 Node.js 和 NPM。本教學建議安裝 Angular CLI:

npm install -g @angular/cli

設定 Angular 項目

首先,讓我們建立一個新的 Angular 專案。在此範例中,我們使用 Angular 版本 15.2.9:

ng new passkeys-demo-angular

在設定過程中,選擇以下選項:

  • 共享假名使用資料:
  • 角度路由:
  • 樣式表格式: CSS
  • 啟用 SSR: 否(如果您的應用程式需要伺服器端渲染,請選擇是)

設定完成後,執行應用程式以確保一切正常:

ng serve

整合 Corbado 進行金鑰身份驗證

1. 設定您的 Corbado 帳戶

首先,在 Corbado 開發者面板上建立一個帳戶。此步驟可讓您親身體驗金鑰註冊。註冊後,選擇「Corbado Complete」作為您的產品,在 Corbado 中建立一個專案。指定「Web 應用程式」作為應用程式類型,對於框架,選擇 Angular。在您的應用程式設定中,使用以下詳細資訊:

  • 應用程式 URL: http://localhost:4200
  • 依賴方 ID: 本機

2. 嵌入Corbado UI元件

接下來,您需要安裝 Corbado 整合所需的軟體包。導航到專案的根目錄並安裝必要的套件:

npm i @corbado/web-js
npm i -D @corbado/types @types/react @types/ua-parser-js

修改app.component.ts以在應用程式啟動時初始化Corbado:

import { Component, OnInit } from '@angular/core';
import Corbado from "@corbado/web-js";

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
    title = 'passkeys-demo-angular';
    isInitialized = false;

    constructor() {
    }

    ngOnInit(): void {
        this.initialize();
    }

    async initialize() {
        try {
            await Corbado.load({
                projectId: "<Your Corbado Project ID>",
                darkMode: 'off'
            });
            this.isInitialized = true;
        } catch (error) {
            console.error('Initialization failed:', error);
        }
    }
}

3. 建立登入和設定檔元件

產生兩個元件:一個用於顯示金鑰登入 UI,另一個用於在驗證成功後顯示基本使用者資訊:

ng generate component login
ng generate component profile

更新您的 app-routing.module.ts 以定義登入和設定檔元件的路由:

// src/app/app-routing.module.ts

import { NgModule } from '@angular/core';
import { ProfileComponent } from "./profile/profile.component";
import { RouterModule, Routes } from "@angular/router";
import { LoginComponent } from "./login/login.component";

const routes: Routes = [
    { path: 'profile', component: ProfileComponent },
    { path: 'login', component: LoginComponent },
    { path: '', component: LoginComponent },
    { path: '**', redirectTo: '/' }
]

@NgModule({
    imports: [
        RouterModule.forRoot(routes)
    ],
    exports: [RouterModule]
})
export class AppRoutingModule {
}

在login.component.ts中,設定金鑰驗證UI並定義成功登入後的行為:

import { Component, OnInit, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import { Router } from '@angular/router';
import Corbado from "@corbado/web-js";

@Component({
    selector: 'app-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit, AfterViewInit {
    @ViewChild('authElement', { static: false }) authElement!: ElementRef;  // Access the element

    constructor(private router: Router) {
    }

    ngOnInit() {
        if (Corbado.user) {
            this.router.navigate(['/profile']);
        }
    }

    ngAfterViewInit() {
        // Mount the Corbado auth UI after the view initializes
        Corbado.mountAuthUI(this.authElement.nativeElement, {
            onLoggedIn: () => this.router.navigate(['/profile']), // Use Angular's router instead of window.location
        });
    }
}

並在login.component.html中加入以下內容:

<div #authElement></div>

4. 設定個人資料頁面

個人資料頁面將顯示基本使用者資訊(使用者 ID 和電子郵件)並提供登出按鈕。如果使用者未登錄,頁面會提示返回首頁:

import { Component } from '@angular/core';
import { Router } from "@angular/router";
import Corbado from "@corbado/web-js";

@Component({
    selector: 'app-profile',
    templateUrl: './profile.component.html',
    styleUrls: ['./profile.component.css']
})
export class ProfileComponent {
    user = Corbado.user

    constructor(private router: Router) {
    }

    async handleLogout() {
        await Corbado.logout()
        await this.router.navigate(['/']);
    }
}

在 profile.component.html 中,根據使用者的驗證狀態有條件地呈現使用者的資訊:

<div>
    <ng-container *ngIf="user; else notLoggedIn">
        <div>
            <h1>Profile Page</h1>
            <div>
                <p>
                    User-ID: {{user.sub}}
                    <br />
                    Email: {{user.email}}
                </p>
            </div>
            <button (click)="handleLogout()">Logout</button>
        </div>
    </ng-container>

    <ng-template #notLoggedIn>
        <div>
            <p>You're not logged in.</p>
            <p>Please go back to <a routerLink="/">home</a> to log in.</p>
        </div>
    </ng-template>
</div>

運行應用程式

一切設定完畢後,執行應用程式:

ng serve

造訪http://localhost:4200查看登入介面,認證成功後將跳到個人資料頁面。

結論

本教學示範如何使用 Corbado 將金鑰驗證整合到 Angular 應用程式中。透過 Corbado 的工具,實現無密碼身份驗證既簡單又安全。有關會話管理和其他高級功能的更多詳細信息,請參閱 Corbado 的文檔或查看詳細的部落格文章。

以上是教學:如何將金鑰整合到 Angular 中的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn