Firebase Token Laravel API

User
const getFirebaseToken = async (provider:string) => {
try {
// Sign in with Google or GitHub
const result = provider === "google" ? await signInWithGoogle() : await signInWithGithub();
//console.log(result);
// Get Firebase ID token
const idToken = await result.user.getIdToken();
console.log(result.user.displayName, result.user.email, result.user.photoURL, result.user.uid);
const userData = {
name: result.user.displayName,
email: result.user.email,
avatar: result.user.photoURL,
firebase_uid: result.user.uid,
id_token: idToken,
};
const response = await publicApi.post(`${apiUrl}/auth/firebase-login`, {
name: result.user.displayName,
email: result.user.email,
avatar: result.user.photoURL,
firebase_uid: result.user.uid,
id_token: idToken,
});
console.log(result.user.displayName);
console.log(response);
if (response.data.success) {
alertMessage.value = "Login successful!";
alertColor.value = 'success';
authStore.setUser(response.data.user, response.data.token);
router.push('/dashboard');
} else {
console.log(response.data);
alertMessage.value = response.data.message;
alertColor.value = 'error';
console.error("Login failed:", response.data.message);
}
} catch (error: any) {
console.log("Error getting Firebase Token:", error);
alertMessage.value = error.response?.data.message;
alertColor.value = 'error';
console.error("Error during login:", error.response?.data.message || error.message);
}
};
above operation token recievied but laravel api call not work
Assistant
If the Firebase token is received, but the Laravel API call (`publicApi.post`) is not working, follow these debugging steps:

### 1. **Check API Endpoint (`apiUrl`)**
Ensure that `apiUrl` is correctly defined. Try logging it before making the request:

console.log("API URL:", apiUrl);

Ensure that the URL is **reachable** in your environment (local, staging, or production).

### 2. **Debug API Call (`publicApi.post`)**
Before sending the request, check if `publicApi` is properly set up:

console.log("Sending data to API:", {
  name: result.user.displayName,
  email: result.user.email,
  avatar: result.user.photoURL,
  firebase_uid: result.user.uid,
  id_token: idToken,
});

This ensures you're sending the correct payload.

### 3. **Check Network Requests in Browser Developer Tools**
– Open **Developer Console** (`F12` or `Ctrl + Shift + I` in Chrome/Firefox).
– Go to the **Network** tab.
– Filter by **XHR** or **Fetch** requests.
– Look for the request to `/auth/firebase-login`.
– Check the **status code** and **response**.

**Common Issues:**
– `404 Not Found` → Check if the Laravel route exists.
– `403 Forbidden` → Check CORS & Authentication.
– `500 Internal Server Error` → Check Laravel logs (`storage/logs/laravel.log`).

### 4. **Verify Laravel API Route**
Ensure your Laravel route exists in `routes/api.php`:

use AppHttpControllersAuthFirebaseAuthController;

Route::post('/auth/firebase-login', [FirebaseAuthController::class, 'firebaseLogin']);

Run:

php artisan route:list | grep firebase-login

If it's missing, **clear cache** and re-run:

php artisan route:clear
php artisan config:clear
php artisan cache:clear

### 5. **Check Laravel Middleware (CORS & Authentication)**
If your Laravel API is rejecting the request, check:
#### **CORS Issue**
If you're calling Laravel from a different domain (like localhost → API server), update `cors.php`:

// config/cors.php
'paths' => ['api/*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,

Then, restart Laravel:

php artisan serve

### 6. **Check Laravel Logs for Errors**
Run:

tail -f storage/logs/laravel.log

or check manually in `storage/logs/laravel.log`.

If there's a **token validation error**, ensure Laravel is correctly verifying Firebase tokens:
#### **Example Laravel Code to Verify Firebase Token**

use KreaitFirebaseAuth as FirebaseAuth;
use IlluminateHttpRequest;
use IlluminateSupportFacadesAuth;

public function firebaseLogin(Request $request, FirebaseAuth $auth)
{
    try {
        $verifiedIdToken = $auth->verifyIdToken($request->id_token);
        $firebaseUid = $verifiedIdToken->claims()->get('sub');

        $user = User::updateOrCreate(
            ['firebase_uid' => $firebaseUid],
            ['name' => $request->name, 'email' => $request->email, 'avatar' => $request->avatar]
        );

        // Generate Laravel token
        $token = $user->createToken('firebase-auth')->plainTextToken;

        return response()->json(['success' => true, 'user' => $user, 'token' => $token]);
    } catch (Exception $e) {
        return response()->json(['success' => false, 'message' => 'Invalid Firebase token'], 401);
    }
}

Make sure you have installed Firebase SDK in Laravel:

composer require kreait/firebase-php

### 7. **Ensure Laravel Accepts JSON Requests**
If Laravel rejects the request, ensure:
– Your controller uses `Request $request`
– Add `Accept: application/json` header in Vue:

const response = await publicApi.post(`${apiUrl}/auth/firebase-login`, userData, {
  headers: {
    "Accept": "application/json",
    "Content-Type": "application/json",
  },
});

### Summary of Fixes:
✅ Check `apiUrl` correctness
✅ Debug `publicApi.post` request
✅ Verify Laravel route (`php artisan route:list`)
✅ Check Laravel logs (`storage/logs/laravel.log`)
✅ Fix CORS issues (`config/cors.php`)
✅ Ensure Firebase token verification works

Try these steps and let me know where it fails! 🚀

User
KreaitFirebaseJWTIdTokenVerifier::__construct(): Argument #1 ($handler) must be of type KreaitFirebaseJWTActionVerifyIdTokenHandler, string given, called in /var/www/html/app/Http/Controllers/API/Auth/FirebaseAuthController.php on line 22
Assistant
Ah, this is a common mistake when using the **Kreait Firebase PHP SDK**.

The issue is that you might be using the old way of instantiating the `IdTokenVerifier`.

### **The cause:**

You're likely doing something like this:

$verifier = new KreaitFirebaseJWTIdTokenVerifier('my-project-id');

However, as of newer versions of `kreait/firebase-php` (>= 6.x), `IdTokenVerifier` no longer accepts a string project ID directly. It now expects a **Handler instance** as the first argument.

### **✅ Correct way:**

If you're already using the main `FirebaseAuth` service, you don't need to manually instantiate the `IdTokenVerifier` anymore. You should use Kreait's built-in service.

### ✅ **Recommended Solution**

Update your controller to use **FirebaseAuth::verifyIdToken()** instead of creating your own verifier.

use KreaitFirebaseAuth as FirebaseAuth;
use IlluminateHttpRequest;

public function firebaseLogin(Request $request, FirebaseAuth $auth)
{
    try {
        // Automatically verifies token with your Firebase project settings
        $verifiedIdToken = $auth->verifyIdToken($request->id_token);

        $firebaseUid = $verifiedIdToken->claims()->get('sub');

        // Proceed with user logic
        $user = User::updateOrCreate(
            ['firebase_uid' => $firebaseUid],
            ['name' => $request->name, 'email' => $request->email, 'avatar' => $request->avatar]
        );

        $token = $user->createToken('firebase-auth')->plainTextToken;

        return response()->json(['success' => true, 'user' => $user, 'token' => $token]);
    } catch (Throwable $e) {
        return response()->json(['success' => false, 'message' => $e->getMessage()], 401);
    }
}

### ✅ **Make sure you bind Firebase in your Laravel service container**

If you are using `kreait/firebase-laravel`:

composer require kreait/laravel-firebase

In your `config/services.php`:

'firebase' => [
    'credentials' => storage_path('firebase/firebase_credentials.json'),
],

Then, you can inject `FirebaseAuth` into your controllers like this:

public function __construct(FirebaseAuth $auth) {
    $this->auth = $auth;
}

### **⛔ Avoid manual `new IdTokenVerifier()` calls**
That pattern is **deprecated** if you're using `kreait/laravel-firebase`.

### **Alternative: If you want to manually verify using JWT package**

use KreaitFirebaseJWTIdTokenVerifier;
use KreaitFirebaseJWTActionVerifyIdToken;
use KreaitFirebaseJWTActionVerifyIdTokenHandler;

$handler = new VerifyIdTokenHandler('https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com');

$verifier = new IdTokenVerifier($handler);

$idToken = $request->id_token;

$verifiedToken = $verifier->verifyIdToken(VerifyIdToken::withProjectIdAndToken('your-project-id', $idToken));

But this is **not recommended** if you're already using `kreait/laravel-firebase`.

### TL;DR:
✅ **Use `$auth->verifyIdToken($token)`**
✅ **Avoid manual `new IdTokenVerifier()`**

Do you want me to also help you configure your `firebase_credentials.json` properly if you haven't done that part yet? 🚀

User
Class "KreaitFirebaseAuth" does not exist
Assistant
This means the Laravel app is **missing the `kreait/laravel-firebase` package**, or it's not properly configured.

### Let's fix it step by step:

### **1️⃣ Install the Laravel Firebase package**

Run this:

composer require kreait/laravel-firebase

### **2️⃣ Publish the config (optional but recommended)**

php artisan vendor:publish --provider="KreaitLaravelFirebaseServiceProvider"

This will create a `config/firebase.php` file.

### **3️⃣ Add Firebase credentials**

You need the **service account JSON file** from Firebase Console.

– Go to [Firebase Console → Project Settings → Service Accounts](https://console.firebase.google.com/)
– Click **"Generate new private key"**
– Download the JSON and save it as:

/storage/app/firebase/firebase_credentials.json

### **4️⃣ Configure `config/firebase.php`**

return [
    'credentials' => [
        'file' => storage_path('app/firebase/firebase_credentials.json'),
    ],
];

### **5️⃣ Inject Firebase Auth**

Now you can use it properly:

use KreaitFirebaseAuth as FirebaseAuth;

public function firebaseLogin(Request $request, FirebaseAuth $auth)
{
    // verify and handle token here...
}

### **6️⃣ Optional: Facade or Container Resolve**

You could also resolve it anywhere via:

$auth = app('firebase.auth');

### ✅ After these steps:
– The **`KreaitFirebaseAuth` class will now exist**.
– You can safely use `$auth->verifyIdToken($idToken)`.

### **7️⃣ Laravel auto-discovery**
No need to add service providers manually as `kreait/laravel-firebase` auto-registers.

⚠ **Tip:**
Ensure your service account JSON has access to Firebase Auth (check IAM roles in Google Cloud Console).

Would you like me to also show you how to handle token expiry and refresh logic next? 🚀

User
now adjust firebase_login
Assistant
Great! Now that the **Firebase SDK is properly installed**, let's adjust the `firebaseLogin` function to work correctly.

### ✅ **Updated `firebaseLogin` Function**
This function will:
– **Verify the Firebase ID Token**
– **Extract user details**
– **Create or update the user in the database**
– **Generate a Laravel API token**
– **Return the user & token in response**

#### **🚀 Corrected `firebaseLogin` Controller Method**

use KreaitFirebaseAuth as FirebaseAuth;
use IlluminateHttpRequest;
use AppModelsUser;
use IlluminateSupportFacadesLog;

public function firebaseLogin(Request $request, FirebaseAuth $auth)
{
    try {
        // Validate the request
        $request->validate([
            'id_token' => 'required|string',
            'name' => 'nullable|string',
            'email' => 'required|email',
            'avatar' => 'nullable|string',
        ]);

        // Verify Firebase ID token
        $verifiedIdToken = $auth->verifyIdToken($request->id_token);

        // Extract Firebase UID
        $firebaseUid = $verifiedIdToken->claims()->get('sub');

        // Log for debugging
        Log::info('Firebase UID:', ['uid' => $firebaseUid]);

        // Check if user exists, if not create one
        $user = User::updateOrCreate(
            ['firebase_uid' => $firebaseUid],
            [
                'name' => $request->name ?? 'Firebase User',
                'email' => $request->email,
                'avatar' => $request->avatar,
                'password' => bcrypt(uniqid()), // Generate random password
            ]
        );

        // Generate Laravel Sanctum token
        $token = $user->createToken('firebase-auth')->plainTextToken;

        return response()->json([
            'success' => true,
            'user' => $user,
            'token' => $token
        ], 200);
    } catch (KreaitFirebaseExceptionAuthInvalidIdToken $e) {
        return response()->json(['success' => false, 'message' => 'Invalid Firebase token'], 401);
    } catch (Exception $e) {
        Log::error('Firebase Login Error:', ['error' => $e->getMessage()]);
        return response()->json(['success' => false, 'message' => 'Login failed'], 500);
    }
}

### 🔍 **How This Works**
– ✅ **Verifies Firebase ID token** using `$auth->verifyIdToken($request->id_token)`
– ✅ **Extracts Firebase UID**
– ✅ **Finds or creates the user** in the Laravel database
– ✅ **Generates Laravel Sanctum API token**
– ✅ **Handles errors properly & logs them**

### 🚀 **Test API Call**
Now, test the Laravel API with **Postman or Axios**:

#### **Example Request**

POST /api/auth/firebase-login
Content-Type: application/json
{
  "id_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjYwZGE3",
  "name": "John Doe",
  "email": "johndoe@example.com",
  "avatar": "https://example.com/avatar.jpg"
}

#### **Expected Response**

{
  "success": true,
  "user": {
    "id": 1,
    "firebase_uid": "abc123",
    "name": "John Doe",
    "email": "johndoe@example.com",
    "avatar": "https://example.com/avatar.jpg",
    "created_at": "2025-03-15T10:00:00.000000Z"
  },
  "token": "7|Hk8J..."
}

### 🔥 **Final Steps**
– **Make sure Laravel is using Sanctum for API authentication**

composer require laravel/sanctum
  php artisan vendor:publish --provider="LaravelSanctumSanctumServiceProvider"
  php artisan migrate

– **Enable Sanctum in `config/auth.php`**

'guards' => [
      'api' => [
          'driver' => 'sanctum',
          'provider' => 'users',
      ],
  ],

– **Add middleware in `app/Http/Kernel.php`**

protected $middlewareGroups = [
      'api' => [
          LaravelSanctumHttpMiddlewareEnsureFrontendRequestsAreStateful::class,
          'throttle:api',
          IlluminateRoutingMiddlewareSubstituteBindings::class,
      ],
  ];

– **Test logging in and fetching user data with the token!**

### 🎯 **Next Steps**
– ✅ Integrate the Laravel API response with your **Vue.js frontend**
– ✅ Store the `token` in **Vuex/Pinia or localStorage**
– ✅ Use the token in all API requests:

axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;

Now, Firebase Login is **fully functional**! 🚀

Let me know if you need more customizations! 😊

User
display all package from composer
Assistant
To display all installed packages from **Composer**, you can use the following command:

### **1️⃣ Show All Installed Composer Packages**
Run this in your project root:

composer show

This will list **all installed Composer packages**, their **versions**, and **descriptions**.

### **2️⃣ Show Installed Packages with Dependencies**
To see **detailed information** about each package, run:

composer show -t

This will display a **tree structure** of dependencies.

### **3️⃣ Export Installed Packages to a File**
To save the list to a text file:

composer show > installed-packages.txt

This creates a file `installed-packages.txt` with all installed packages.

### **4️⃣ Check Installed Packages in `composer.json`**
If you just want the packages **you explicitly installed** (not dependencies), check:

cat composer.json

or

jq .require composer.json

(This works if `jq` is installed)

### **5️⃣ Check Installed Packages with Version Constraints**
Run:

composer show --installed

This will list all installed packages along with their version constraints.

### **6️⃣ Check Only Laravel-related Packages**
To list only Laravel-related packages, run:

composer show | grep laravel

Would you like me to help analyze a specific package or check for outdated ones? 🚀

User
we have this installed already
kreait/firebase-tokens
Assistant
Since you already have `kreait/firebase-tokens` installed but are missing `KreaitFirebaseAuth`, it means the **full Firebase SDK** is not installed.

### **Fix: Install the Full Firebase SDK**
Run:

composer require kreait/firebase-php

This will install the entire **Firebase Admin SDK**, including:
– `KreaitFirebaseAuth`
– `KreaitFirebaseDatabase`
– `KreaitFirebaseMessaging`
– `KreaitFirebaseStorage`
– Other Firebase services.

### **Verify Installation**
After installation, check if `KreaitFirebaseAuth` exists:

composer show | grep kreait

Expected output:

kreait/firebase-php v6.x Firebase Admin SDK for PHP
kreait/firebase-tokens v3.x A library to verify Firebase authentication tokens

### **Use Firebase Auth in Laravel**
Now, you can use `KreaitFirebaseAuth` in your Laravel controller:

use KreaitFirebaseAuth as FirebaseAuth;

public function firebaseLogin(Request $request, FirebaseAuth $auth)
{
    try {
        $verifiedIdToken = $auth->verifyIdToken($request->id_token);
        $firebaseUid = $verifiedIdToken->claims()->get('sub');

        $user = User::updateOrCreate(
            ['firebase_uid' => $firebaseUid],
            ['name' => $request->name, 'email' => $request->email, 'avatar' => $request->avatar]
        );

        $token = $user->createToken('firebase-auth')->plainTextToken;

        return response()->json(['success' => true, 'user' => $user, 'token' => $token]);
    } catch (Throwable $e) {
        return response()->json(['success' => false, 'message' => $e->getMessage()], 401);
    }
}

### **Clear Cache (If Needed)**
If `KreaitFirebaseAuth` still isn't recognized, clear Composer's cache:

composer clear-cache
composer dump-autoload

Now try again! 🚀
If you still have issues, let me know what error appears. 😊

Leave a Comment

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