首页 > web前端 > js教程 > 正文

教程:如何将密钥集成到 Angular 中

王林
发布: 2024-08-28 06:10:36
原创
1013 人浏览过

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中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!