You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中使用kreait/firebase-php生成Firebase自定义令牌格式错误求助

Fixing "The custom token format is incorrect" Error in Laravel with kreait/firebase-php

Looks like you're hitting a common pitfall when generating Firebase custom tokens with the kreait/firebase-php library in Laravel. Let's break down the possible causes and fixes for this error:

1. Validate the UID Format

Firebase enforces strict rules for custom token UIDs:

  • Must be a string between 1 and 128 characters long
  • Cannot contain characters like ,, #, $, [, ], or @

In your current code, you're using the hardcoded string "id" as the UID. While this is technically valid, it's better to use your authenticated user's actual unique identifier (like $user->id) to ensure uniqueness and compliance. Update that line to:

$customToken = $firebase->getAuth()->createCustomToken(strval($user->id));

(Use strval() to ensure it's a string, even if your user ID is numeric)

2. Verify Your Service Account File

A corrupted or missing service account JSON file is a frequent culprit here:

  • Double-check that service_account.json is downloaded directly from your Firebase Project Settings > Service Accounts > Generate New Private Key
  • Confirm the file path __DIR__.'/service_account.json' is correct. You can add a quick check to catch missing files:
$serviceAccountPath = __DIR__.'/service_account.json';
if (!file_exists($serviceAccountPath)) {
    return response()->json(["error" => "Service account file not found"], 400);
}

Ensure the file contains valid fields like private_key, client_email, and project_id—missing or malformed values will break token generation.

3. Check Library Version Compatibility

Outdated versions of kreait/firebase-php can cause compatibility issues with Firebase's API. Run this command to update to the latest stable version:

composer update kreait/firebase-php

Make sure the version you're using is compatible with your Laravel version (check the library's GitHub README for version matrix details).

4. Ensure Proper Token Serialization

Sometimes the generated token might be returned as an object instead of a string, which can cause formatting issues when sent as JSON. Explicitly cast it to a string in your response:

return response()->json(["custom_token" => (string)$customToken]);

Debugging Tip

To confirm the token structure is valid, copy the generated token and paste it into JWT.io (use the tool to inspect locally). A valid Firebase custom token should have:

  • Header: alg: RS256 and kid matching your service account's key ID
  • Payload: Contains iss (your service account's client email), sub (same as iss), aud (set to https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit), and your specified uid

Updated Working Code

Here's a revised version of your function incorporating all these fixes:

public function getToken(){
    $user = Auth::user();
    
    // Validate service account file exists
    $serviceAccountPath = __DIR__.'/service_account.json';
    if (!file_exists($serviceAccountPath)) {
        return response()->json(["error" => "Service account file not found"], 400);
    }
    
    $serviceAccount = ServiceAccount::fromJsonFile($serviceAccountPath);
    $firebase = (new Factory)->withServiceAccount($serviceAccount)->create();
    
    try {
        // Use user's actual UID and optional custom claims
        $customToken = $firebase->getAuth()->createCustomToken(strval($user->id), [
            'email' => $user->email,
            'name' => $user->name
        ]);
        
        // Return token as string
        return response()->json(["custom_token" => (string)$customToken]);
    } catch (\Exception $e) {
        return response()->json(["error" => $e->getMessage()], 500);
    }
}

内容的提问来源于stack exchange,提问作者Kamal Oli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:29:33