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

Firebase消息推送Symfony集成Oauth2 401认证凭证无效问题

解决Firebase Messaging v1 API Symfony集成401无效凭证问题

核心问题分析

你的代码存在三个关键错误导致认证失败:

  • 令牌字段误用:FCM v1 API要求使用access_token,而非你代码里的id_token
  • Scope URL错误:正确的FCM权限范围是https://www.googleapis.com/auth/firebase.messaging,你遗漏了www.前缀
  • 配置路径不安全:Symfony中直接使用相对路径../config/可能因运行环境差异导致文件读取失败

修复步骤

1. 修正令牌与Scope逻辑

修改ServiceAccountCredentials初始化和令牌调用逻辑,替换为正确的参数:

namespace App\Service\Firebase;

use App\Service\AbstractApiClient;
use Exception;
use Google\Auth\Credentials\ServiceAccountCredentials;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;

class MessagingService extends AbstractApiClient
{
    private string $configDir;

    // 通过构造注入配置目录,避免硬编码路径
    public function __construct(string $configDir)
    {
        $this->configDir = $configDir;
    }

    /**
     * @throws TransportExceptionInterface
     * @throws Exception
     */
    public function send(string $project, array $body): ResponseInterface
    {
        // 修正Scope URL,添加www.前缀
        $credential = new ServiceAccountCredentials(
            'https://www.googleapis.com/auth/firebase.messaging',
            json_decode(file_get_contents($this->getConfigPath($project)), true)
        );

        $token = $credential->fetchAuthToken();

        $firebaseUrl = 'https://fcm.googleapis.com/v1/projects/' . $project . '/messages:send';

        return $this->request(
            Request::METHOD_POST,
            $firebaseUrl,
            [
                'headers' => [
                    'Content-Type' => 'application/json',
                    // 替换为access_token字段
                    'Authorization' => 'Bearer ' . $token['access_token']
                ],
                'body' => json_encode($body) // 确保body是标准JSON字符串
            ]
        );
    }

    /**
     * 安全获取配置文件路径
     */
    private function getConfigPath(string $project): string
    {
        return sprintf('%s/%s/config.json', $this->configDir, $project);
    }
}

2. 配置Symfony服务参数

在services.yaml中注入配置目录路径,避免硬编码:

services:
    App\Service\Firebase\MessagingService:
        arguments:
            $configDir: '%kernel.project_dir%/config/firebase'

3. 验证文件权限

确保config.json文件的权限正确,Symfony运行用户(如www-data)拥有读取权限,避免因文件无法加载导致的凭证失效。

验证效果

修复后生成的令牌会以ya29开头,与Postman生成的格式一致,此时调用FCM API即可正常推送通知。

内容的提问来源于stack exchange,提问作者Kevin Guillier

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 20:42:02