返回

NestJS应用程序中Firebase认证的无忧体验

见解分享

前言

在现代Web开发中,身份验证是确保用户数据和隐私安全的关键。在NestJS应用程序中集成Firebase认证,是构建健壮可靠的认证系统的便捷之选。Firebase提供了一整套灵活易用的认证工具,使您能够快速、轻松地实现用户注册、登录和注销等功能。

集成Firebase认证

1. 项目设置

  • 首先,前往Firebase控制台并创建一个新项目。
  • 在"身份验证"标签页下,启用电子邮件/密码和谷歌认证方式。
  • 在"项目设置"标签页下,复制API密钥、项目ID和测量ID。

2. 安装Firebase依赖

  • 在NestJS项目中,安装Firebase Admin SDK和NestJS Firebase模块。
npm install firebase-admin @nestjs/firebase

3. 配置Firebase Admin

  • 在项目根目录下创建一个新的文件名为firebase-admin.ts,并将以下内容粘贴进去:
import { initializeApp, FirebaseOptions } from "firebase-admin/app";

const firebaseOptions: FirebaseOptions = {
  credential: applicationDefault(),
  projectId: 'your-project-id',
};

initializeApp(firebaseOptions);
  • your-project-id替换为您的Firebase项目ID。

4. 创建认证服务

  • 在NestJS应用程序中创建一个新的服务类名为AuthService,并将以下内容粘贴进去:
import { Injectable } from "@nestjs/common";
import { Auth, UserRecord } from "firebase-admin/auth";

@Injectable()
export class AuthService {
  private readonly auth: Auth;

  constructor() {
    this.auth = getAuth();
  }

  async createUser(email: string, password: string): Promise<UserRecord> {
    return await this.auth.createUser({
      email,
      password,
    });
  }

  async verifyPassword(email: string, password: string): Promise<boolean> {
    const user = await this.auth.getUserByEmail(email);
    return await this.auth.verifyPassword(user.uid, password);
  }

  async generateAuthToken(email: string, password: string): Promise<string> {
    const user = await this.auth.getUserByEmail(email);
    const token = await this.auth.createCustomToken(user.uid);
    return token;
  }
}

结语

通过Firebase认证,您可以轻松地向NestJS应用程序添加安全验证层,确保用户数据和隐私的安全。无论是构建全新的应用程序还是为现有应用程序添加认证功能,Firebase都是一个值得信赖的选择。