Home  >  Article  >  Web Front-end  >  Tutorial: How to Integrate Passkeys into Angular

Tutorial: How to Integrate Passkeys into Angular

王林
王林Original
2024-08-28 06:10:361092browse

Tutorial: How to Integrate Passkeys into Angular

Implementing Passkey Authentication in Angular with TypeScript

In this guide, we’ll walk through the process of integrating passkey authentication into an Angular application using TypeScript. Passkeys provide a secure and scalable way to manage user authentication, removing the need for traditional passwords.

View full tutorial in our original blog post here

Prerequisites

Before starting, ensure you’re familiar with Angular, HTML, CSS, and TypeScript. Additionally, make sure you have Node.js and NPM installed on your machine. Installing the Angular CLI is recommended for this tutorial:

npm install -g @angular/cli

Setting Up the Angular Project

First, let’s create a new Angular project. In this example, we’re using Angular version 15.2.9:

ng new passkeys-demo-angular

During setup, choose the following options:

  • Share pseudonymous usage data: No
  • Angular routing: Yes
  • Stylesheet format: CSS
  • Enable SSR: No (Choose Yes if your application requires server-side rendering)

Once the setup is complete, run the application to ensure everything is functioning:

ng serve

Integrating Corbado for Passkey Authentication

1. Set Up Your Corbado Account

To start, create an account on the Corbado developer panel. This step allows you to experience passkey signup firsthand. After registering, create a project within Corbado by selecting “Corbado Complete” as your product. Specify “Web app” as the application type, and for the framework, select Angular. In your application settings, use the following details:

  • Application URL: http://localhost:4200
  • Relying Party ID: localhost

2. Embedding the Corbado UI Component

Next, you’ll need to install the required packages for Corbado integration. Navigate to your project’s root directory and install the necessary packages:

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

Modify the app.component.ts to initialize Corbado when the application starts:

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. Creating Login and Profile Components

Generate two components: one for displaying the passkey login UI and another for showing basic user information upon successful authentication:

ng generate component login
ng generate component profile

Update your app-routing.module.ts to define routes for the login and profile components:

// 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 {
}

In login.component.ts, set up the passkey authentication UI and define the behavior after a successful login:

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
        });
    }
}

And in the login.component.html, add the following:

<div #authElement></div>

4. Setting Up the Profile Page

The profile page will display basic user information (user ID and email) and provide a logout button. If the user isn’t logged in, the page will prompt them to return to the home page:

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(['/']);
    }
}

In profile.component.html, conditionally render the user’s information based on their authentication state:

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

Running the Application

Once everything is set up, run the application:

ng serve

Visit http://localhost:4200 to view the login screen, and after successful authentication, you will be redirected to the profile page.

Conclusion

This tutorial demonstrated how to integrate passkey authentication into an Angular application using Corbado. With Corbado’s tools, implementing passwordless authentication is straightforward and secure. For more details on session management and other advanced features, refer to Corbado’s documentation or check the detailed blog post.

The above is the detailed content of Tutorial: How to Integrate Passkeys into Angular. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn