Step-by-Step Angular Authentication Setup with Firebase and AngularFire

Implementing user authentication in Angular applications is essential for securing your app and providing personalized experiences. Firebase, combined with AngularFire, offers a seamless way to integrate authentication features into your Angular project. This guide walks you through the step-by-step process to set up Angular authentication with Firebase and AngularFire.

Prerequisites

  • Basic knowledge of Angular framework
  • Node.js and npm installed
  • Angular CLI installed
  • Firebase account

Step 1: Create a Firebase Project

Go to the Firebase Console and create a new project. Follow the prompts to set up your project. Once created, navigate to the project dashboard.

Enable Authentication Method

In the Firebase console, select “Authentication” from the menu. Click on the “Sign-in method” tab and enable the desired authentication providers, such as Email/Password, Google, or Facebook.

Step 2: Register Your Angular App with Firebase

In the Firebase console, go to “Project Settings” and click on “Add app”. Choose the web icon, provide a nickname, and register your app. Firebase will generate your app’s Firebase configuration object.

Step 3: Set Up Angular Project

Create a new Angular project or navigate to your existing project directory. Install AngularFire and Firebase packages:

npm install @angular/fire firebase

Step 4: Configure AngularFire

Import AngularFire modules in your app.module.ts and initialize Firebase with your configuration:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AngularFireModule } from '@angular/fire/compat';
import { environment } from '../environments/environment';

@NgModule({
  declarations: [...],
  imports: [
    BrowserModule,
    AngularFireModule.initializeApp(environment.firebaseConfig),
    // other imports
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Add your Firebase configuration to environment.ts:

export const environment = {
  production: false,
  firebaseConfig: {
    apiKey: "YOUR_API_KEY",
    authDomain: "YOUR_AUTH_DOMAIN",
    projectId: "YOUR_PROJECT_ID",
    storageBucket: "YOUR_STORAGE_BUCKET",
    messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
    appId: "YOUR_APP_ID"
  }
};

Step 5: Create Authentication Service

Create a service to handle authentication logic:

import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/compat/auth';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  user$: Observable;

  constructor(private afAuth: AngularFireAuth) {
    this.user$ = this.afAuth.authState;
  }

  login(email: string, password: string): Promise {
    return this.afAuth.signInWithEmailAndPassword(email, password);
  }

  logout(): Promise {
    return this.afAuth.signOut();
  }

  register(email: string, password: string): Promise {
    return this.afAuth.createUserWithEmailAndPassword(email, password);
  }
}

Step 6: Create Authentication Components

Create components for login, registration, and profile management as needed. For example, a simple login component:

import { Component } from '@angular/core';
import { AuthService } from '../services/auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html'
})
export class LoginComponent {
  email: string = '';
  password: string = '';

  constructor(private authService: AuthService) {}

  onLogin() {
    this.authService.login(this.email, this.password)
      .then(() => {
        // handle successful login
      })
      .catch(error => {
        // handle errors
      });
  }
}

Step 7: Protect Routes and Handle Authentication State

Use Angular route guards to restrict access to certain pages based on authentication status. Subscribe to authState in your components to reactively display user info or redirect unauthenticated users.

Conclusion

Setting up authentication in Angular with Firebase and AngularFire is straightforward and powerful. With these steps, you can implement secure login, registration, and user management features in your Angular applications, enhancing both security and user experience.