Creating social login using Firebase in an Ionic Angular app

·

, , ,
Creating social login using Firebase in an Ionic Angular app

Hello guys how are you? Welcome back on my blog Therichpost. Today in this post I am going to share Creating social login using Firebase in an Ionic Angular app.

Angular 19 came. If you are new then you must check below two links:

Now guys here is the complete code snippet and please follow carefully:

Creating social login using Firebase in an Ionic Angular app involves integrating Firebase Authentication with providers like Google, Facebook, or Apple. Below is a step-by-step guide to achieve this.


Step 1: Set Up Firebase

  1. Go to the Firebase Console and create a new project.
  2. Navigate to the Authentication section and enable the desired authentication providers (e.g., Google, Facebook, or Apple).
  • For Google, simply enable it and provide the necessary project details.
  • For Facebook or Apple, provide additional credentials like the app ID, app secret, or Service ID.

Step 2: Install Required Dependencies

  1. Install Firebase SDK and AngularFire:
   npm install firebase @angular/fire
  1. Add Firebase configuration in environments/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 3: Import Firebase Modules

  1. Open app.module.ts and add Firebase modules:
   import { AngularFireModule } from '@angular/fire/compat';
   import { AngularFireAuthModule } from '@angular/fire/compat/auth';
   import { environment } from '../environments/environment';

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

Step 4: Add Social Login Logic

Create an AuthService to manage authentication logic.

auth.service.ts

import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/compat/auth';
import firebase from 'firebase/compat/app';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  constructor(private afAuth: AngularFireAuth) {}

  // Google Login
  async googleLogin() {
    try {
      const provider = new firebase.auth.GoogleAuthProvider();
      const result = await this.afAuth.signInWithPopup(provider);
      return result.user; // Returns the logged-in user details
    } catch (error) {
      console.error('Error during Google login:', error);
      throw error;
    }
  }

  // Facebook Login
  async facebookLogin() {
    try {
      const provider = new firebase.auth.FacebookAuthProvider();
      const result = await this.afAuth.signInWithPopup(provider);
      return result.user;
    } catch (error) {
      console.error('Error during Facebook login:', error);
      throw error;
    }
  }

  // Logout
  async logout() {
    await this.afAuth.signOut();
  }
}

Step 5: Create a Login Page

Generate a login page using Ionic CLI:

ionic generate page login

login.page.html

<ion-header>
  <ion-toolbar>
    <ion-title>Login</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content class="ion-padding">
  <ion-button expand="block" (click)="loginWithGoogle()">Login with Google</ion-button>
  <ion-button expand="block" color="secondary" (click)="loginWithFacebook()">Login with Facebook</ion-button>
</ion-content>

login.page.ts

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

@Component({
  selector: 'app-login',
  templateUrl: './login.page.html',
  styleUrls: ['./login.page.scss'],
})
export class LoginPage {
  constructor(private authService: AuthService) {}

  async loginWithGoogle() {
    try {
      const user = await this.authService.googleLogin();
      console.log('Google User:', user);
    } catch (error) {
      console.error('Google Login Error:', error);
    }
  }

  async loginWithFacebook() {
    try {
      const user = await this.authService.facebookLogin();
      console.log('Facebook User:', user);
    } catch (error) {
      console.error('Facebook Login Error:', error);
    }
  }
}

Step 6: Test Your App

  1. Run the app:
   ionic serve
  1. Test the login functionality with Google and Facebook.

Optional: Add Platform-Specific Support

If you plan to deploy your app on mobile platforms (iOS/Android), use @capacitor-firebase/auth for better integration with native features:

  1. Install Capacitor Firebase Auth:
   npm install @capacitor-firebase/auth
  1. Configure native login flows using Capacitor plugins for Google and Facebook.

Let me know if you’d like details on the native configuration!

Ajay

Thanks

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.