DEV Community

Cover image for Seamless Authentication: Integrating Firebase with Laravel
Roshdi Raed
Roshdi Raed

Posted on

Seamless Authentication: Integrating Firebase with Laravel

In the evolving landscape of web development, secure and scalable authentication systems are crucial. Traditional authentication methods, such as Laravel’s built-in authentication with JWT, are robust but can be complex to manage. A modern alternative is Firebase Authentication, a cloud-based solution offering seamless user management, cross-platform support, and enhanced security. This report outlines how Firebase Authentication can replace Laravel’s native authentication system while streamlining the login and registration processes.


What We Did

1. Removing Traditional Laravel Authentication

To ensure a clean integration, we first removed the existing JWT-based authentication system, which included:

Deleting the AuthController.php file (or modifying it to use Firebase).

Removing JWT dependencies from composer.json.

Cleaning up middleware references related to JWT authentication.

Updating routes in web.php and api.php to reflect Firebase authentication.

2. Setting Up Firebase in Laravel

To integrate Firebase Authentication, we followed these key steps:

Step 1: Create a Firebase Project

Go to Firebase Console.

Create a new project and set up Authentication.

Enable Email/Password Authentication (or any other preferred method).

Obtain the Firebase Web API Key from the project settings.

Step 2: Install Firebase SDK

Since Laravel does not have built-in Firebase support, we used Google’s official SDK:

composer require kreait/laravel-firebase
Enter fullscreen mode Exit fullscreen mode

Step 3: Configure Firebase in Laravel

In the .env file, we added the Firebase credentials:

FIREBASE_CREDENTIALS=storage_path('firebase_credentials.json')
Enter fullscreen mode Exit fullscreen mode

The firebase_credentials.json file (downloaded from Firebase) contains essential authentication keys.

3. Implementing Authentication Methods

We replaced traditional authentication methods with Firebase Authentication.

Registering a New User

Instead of storing user passwords manually, we now register users directly in Firebase:

use Kreait\Firebase\Auth;

public function register(Request $request, Auth $auth)
{
    $userProperties = [
        'email' => $request->email,
        'password' => $request->password,
        'displayName' => $request->name
    ];

    $createdUser = $auth->createUser($userProperties);
    return response()->json($createdUser);
}
Enter fullscreen mode Exit fullscreen mode

Logging in a User

We authenticate users through Firebase instead of Laravel’s local authentication system:

public function login(Request $request, Auth $auth)
{
    try {
        $signInResult = $auth->signInWithEmailAndPassword($request->email, $request->password);
        return response()->json($signInResult->data());
    } catch (Exception $e) {
        return response()->json(['error' => 'Invalid credentials'], 401);
    }
}
Enter fullscreen mode Exit fullscreen mode

Fetching the Authenticated User

Firebase tokens can be used to verify and retrieve user information:

public function me(Request $request, Auth $auth)
{
    $idTokenString = $request->bearerToken();
    $verifiedIdToken = $auth->verifyIdToken($idTokenString);
    return response()->json($verifiedIdToken->claims());
}
Enter fullscreen mode Exit fullscreen mode

4. Securing Routes with Middleware

We ensured only authenticated users could access certain routes by creating Firebase-based authentication middleware:

public function handle($request, Closure $next, Auth $auth)
{
    if (!$request->bearerToken()) {
        return response()->json(['error' => 'Unauthorized'], 401);
    }

    try {
        $auth->verifyIdToken($request->bearerToken());
        return $next($request);
    } catch (Exception $e) {
        return response()->json(['error' => 'Invalid token'], 401);
    }
}
Enter fullscreen mode Exit fullscreen mode

5. Updating Frontend for Firebase Authentication

If the Laravel application uses a frontend (such as Vue.js or React), we implemented Firebase Authentication directly using the Firebase SDK:

import { getAuth, signInWithEmailAndPassword } from 'firebase/auth';

const auth = getAuth();
signInWithEmailAndPassword(auth, email, password)
  .then((userCredential) => console.log(userCredential.user))
  .catch((error) => console.error(error.message));
Enter fullscreen mode Exit fullscreen mode

Why Firebase?

✅ Scalability: Supports millions of users with minimal setup.

✅ Security: Offers built-in OAuth and multi-factor authentication.

✅ Cross-Platform: Works seamlessly with web and mobile applications.

✅ Ease of Use: Reduces backend authentication logic.


Conclusion

By replacing Laravel’s native authentication with Firebase Authentication, we achieved a simplified, secure, and scalable authentication system. This integration not only reduced backend complexity but also enhanced security and performance. Whether for small projects or enterprise applications, Firebase provides a powerful alternative to traditional authentication mechanisms.

🚀 Next Steps: Explore Firebase features like real-time databases, push notifications, and analytics to further enhance your Laravel application!

API Trace View

How I Cut 22.3 Seconds Off an API Call with Sentry 👀

Struggling with slow API calls? Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay