”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 教程:如何将密钥集成到 Angular 中

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

发布于2024-08-29
浏览:408

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: localhost

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: "",
                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中添加以下内容:

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中,根据用户的身份验证状态有条件地呈现用户的信息:

Profile Page

User-ID: {{user.sub}}
Email: {{user.email}}

You're not logged in.

Please go back to home to log in.

运行应用程序

一切设置完毕后,运行应用程序:

ng serve

访问http://localhost:4200查看登录界面,认证成功后将跳转至个人资料页面。

结论

本教程演示了如何使用 Corbado 将密钥身份验证集成到 Angular 应用程序中。借助 Corbado 的工具,实现无密码身份验证既简单又安全。有关会话管理和其他高级功能的更多详细信息,请参阅 Corbado 的文档或查看详细的博客文章。

版本声明 本文转载于:https://dev.to/corbado/tutorial-how-to-integrate-passkeys-into-angular-493p?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 如何使用FormData()处理多个文件上传?
    如何使用FormData()处理多个文件上传?
    )处理多个文件输入时,通常需要处理多个文件上传时,通常是必要的。 The fd.append("fileToUpload[]", files[x]); method can be used for this purpose, allowing you to send multi...
    编程 发布于2025-03-12
  • HTML格式标签
    HTML格式标签
    HTML 格式化元素 **HTML Formatting is a process of formatting text for better look and feel. HTML provides us ability to format text without us...
    编程 发布于2025-03-12
  • 如何在JavaScript对象中动态设置键?
    如何在JavaScript对象中动态设置键?
    在尝试为JavaScript对象创建动态键时,如何使用此Syntax jsObj['key' i] = 'example' 1;不工作。正确的方法采用方括号: jsobj ['key''i] ='example'1; 在JavaScript中,数组是一...
    编程 发布于2025-03-12
  • 如何使用Regex在PHP中有效地提取括号内的文本
    如何使用Regex在PHP中有效地提取括号内的文本
    php:在括号内提取文本在处理括号内的文本时,找到最有效的解决方案是必不可少的。一种方法是利用PHP的字符串操作函数,如下所示: 作为替代 $ text ='忽略除此之外的一切(text)'; preg_match('#((。 &&& [Regex使用模式来搜索特...
    编程 发布于2025-03-12
  • 如何使用不同数量列的联合数据库表?
    如何使用不同数量列的联合数据库表?
    合并列数不同的表 当尝试合并列数不同的数据库表时,可能会遇到挑战。一种直接的方法是在列数较少的表中,为缺失的列追加空值。 例如,考虑两个表,表 A 和表 B,其中表 A 的列数多于表 B。为了合并这些表,同时处理表 B 中缺失的列,请按照以下步骤操作: 确定表 B 中缺失的列,并将它们添加到表的末...
    编程 发布于2025-03-12
  • 如何从Python中的字符串中删除表情符号:固定常见错误的初学者指南?
    如何从Python中的字符串中删除表情符号:固定常见错误的初学者指南?
    从python import codecs import codecs import codecs 导入 text = codecs.decode('这狗\ u0001f602'.encode('utf-8'),'utf-8') 印刷(文字)#带有...
    编程 发布于2025-03-12
  • 如何使用组在MySQL中旋转数据?
    如何使用组在MySQL中旋转数据?
    在关系数据库中使用mySQL组使用mySQL组进行查询结果,在关系数据库中使用MySQL组,转移数据的数据是指重新排列的行和列的重排以增强数据可视化。在这里,我们面对一个共同的挑战:使用组的组将数据从基于行的基于列的转换为基于列。 Let's consider the following ...
    编程 发布于2025-03-12
  • 如何克服PHP的功能重新定义限制?
    如何克服PHP的功能重新定义限制?
    克服PHP的函数重新定义限制在PHP中,多次定义一个相同名称的函数是一个no-no。尝试这样做,如提供的代码段所示,将导致可怕的“不能重新列出”错误。 但是,PHP工具腰带中有一个隐藏的宝石:runkit扩展。它使您能够灵活地重新定义函数。 runkit_function_renction_re...
    编程 发布于2025-03-12
  • 为什么使用Firefox后退按钮时JavaScript执行停止?
    为什么使用Firefox后退按钮时JavaScript执行停止?
    导航历史记录问题:JavaScript使用Firefox Back Back 此行为是由浏览器缓存JavaScript资源引起的。要解决此问题并确保在后续页面访问中执行脚本,Firefox用户应设置一个空功能。 警报'); }; alert('inline Alert')...
    编程 发布于2025-03-12
  • 如何从PHP中的数组中提取随机元素?
    如何从PHP中的数组中提取随机元素?
    从阵列中的随机选择,可以轻松从数组中获取随机项目。考虑以下数组:; 从此数组中检索一个随机项目,利用array_rand( array_rand()函数从数组返回一个随机键。通过将$项目数组索引使用此键,我们可以从数组中访问一个随机元素。这种方法为选择随机项目提供了一种直接且可靠的方法。
    编程 发布于2025-03-12
  • 版本5.6.5之前,使用current_timestamp与时间戳列的current_timestamp与时间戳列有什么限制?
    版本5.6.5之前,使用current_timestamp与时间戳列的current_timestamp与时间戳列有什么限制?
    在时间戳列上使用current_timestamp或MySQL版本中的current_timestamp或在5.6.5 此限制源于遗留实现的关注,这些限制需要对当前的_timestamp功能进行特定的实现。 创建表`foo`( `Productid` int(10)unsigned not n...
    编程 发布于2025-03-12
  • 如何使用PHP从XML文件中有效地检索属性值?
    如何使用PHP从XML文件中有效地检索属性值?
    从php $xml = simplexml_load_file($file); foreach ($xml->Var[0]->attributes() as $attributeName => $attributeValue) { echo $attributeName,...
    编程 发布于2025-03-12
  • 如何从Google API中检索最新的jQuery库?
    如何从Google API中检索最新的jQuery库?
    从Google APIS 问题中提供的jQuery URL是版本1.2.6。对于检索最新版本,以前有一种使用特定版本编号的替代方法,它是使用以下语法:获取最新版本:未压缩)While these legacy URLs still remain in use, it is recommended ...
    编程 发布于2025-03-12
  • 如何干净地删除匿名JavaScript事件处理程序?
    如何干净地删除匿名JavaScript事件处理程序?
    删除匿名事件侦听器将匿名事件侦听器添加到元素中会提供灵活性和简单性,但是当要删除它们时,可以构成挑战,而无需替换元素本身就可以替换一个问题。 element? element.addeventlistener(event,function(){/在这里工作/},false); 要解决此问题,请考虑...
    编程 发布于2025-03-12
  • 哪种方法更有效地用于点 - 填点检测:射线跟踪或matplotlib \的路径contains_points?
    哪种方法更有效地用于点 - 填点检测:射线跟踪或matplotlib \的路径contains_points?
    在Python Matplotlib's path.contains_points FunctionMatplotlib's path.contains_points function employs a path object to represent the polygon.它...
    编程 发布于2025-03-12

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3