定制 kreait/firebase-tokens 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

kreait/firebase-tokens

Composer 安装命令:

composer require kreait/firebase-tokens

包简介

A library to work with Firebase tokens

README 文档

README

A library to work with Google Firebase tokens. You can use it to create custom tokens and verify ID Tokens.

Achieve more with the Firebase Admin SDK for PHP (which uses this library).

Current version Supported PHP version Monthly Downloads Total Downloads Tests Sponsor

Important

Support the project: This library is downloaded 1M+ times monthly and powers thousands of applications. If it saves you or your team time, please consider sponsoring its development.

Note

The project moved from the kreait to the beste GitHub Organization in January 2026. The namespace remains Kreait\Firebase\JWT and the package name remains kreait/firebase-tokens. Please update your remote URL if you have forked or cloned the repository.

Installation

composer require kreait/firebase-tokens

Simple usage

Create a custom token

More information on what a custom token is and how it can be used can be found in Google's official documentation.

<?php

use Kreait\Firebase\JWT\CustomTokenGenerator;

$clientEmail = '...';
$privateKey = '...';

$generator = CustomTokenGenerator::withClientEmailAndPrivateKey($clientEmail, $privateKey);
$token = $generator->createCustomToken('uid', ['first_claim' => 'first_value' /* ... */]);

echo $token;
// Output: eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.e...

Verify an ID token

The ID token verification methods included in the Firebase Admin SDKs are meant to verify ID tokens that come from the client SDKs, not the custom tokens that you create with the Admin SDKs. See Auth tokens for more information.

<?php

use Kreait\Firebase\JWT\Error\IdTokenVerificationFailed;
use Kreait\Firebase\JWT\IdTokenVerifier;

$projectId = '...';
$idToken = 'eyJhb...'; // An ID token given to your backend by a Client application

$verifier = IdTokenVerifier::createWithProjectId($projectId);

try {
    $token = $verifier->verifyIdToken($idToken);
} catch (IdTokenVerificationFailed $e) {
    echo $e->getMessage();
    // Example Output:
    // The value 'eyJhb...' is not a verified ID token:
    // - The token is expired.
    exit;
}

try {
    $token = $verifier->verifyIdTokenWithLeeway($idToken, $leewayInSeconds = 10000000);
} catch (IdTokenVerificationFailed $e) {
    print $e->getMessage();
    exit;
}

Verify a Session Cookie

Session cookie verification is similar to ID Token verification.

See Manage Session Cookies for more information.

<?php

use Kreait\Firebase\JWT\Error\SessionCookieVerificationFailed;
use Kreait\Firebase\JWT\SessionCookieVerifier;

$projectId = '...';
$sessionCookie = 'eyJhb...'; // A session cookie given to your backend by a Client application

$verifier = SessionCookieVerifier::createWithProjectId($projectId);

try {
    $token = $verifier->verifySessionCookie($sessionCookie);
} catch (SessionCookieVerificationFailed $e) {
    echo $e->getMessage();
    // Example Output:
    // The value 'eyJhb...' is not a verified ID token:
    // - The token is expired.
    exit;
}

try {
    $token = $verifier->verifySessionCookieWithLeeway($sessionCookie, $leewayInSeconds = 10000000);
} catch (SessionCookieVerificationFailed $e) {
    print $e->getMessage();
    exit;
}

Tokens

Tokens returned from the Generator and Verifier are instances of \Kreait\Firebase\JWT\Contract\Token and represent a JWT. The displayed outputs are examples and vary depending on the information associated with the given user in your project's auth database.

According to the JWT specification, you can expect the following payload fields to be always available: iss, aud, auth_time, sub, iat, exp. Other fields depend on the authentication method of the given account and the information stored in your project's Auth database.

$token = $verifier->verifyIdToken('eyJhb...'); // An ID token given to your backend by a Client application

echo json_encode($token->headers(), JSON_PRETTY_PRINT);
// {
//     "alg": "RS256",
//     "kid": "e5a91d9f39fa4de254a1e89df00f05b7e248b985",
//     "typ": "JWT"
// }                                                   

echo json_encode($token->payload(), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
// {
//     "name": "Jane Doe",
//     "picture": "https://domain.tld/picture.jpg",
//     "iss": "https://securetoken.google.com/your-project-id",
//     "aud": "your-project-id",
//     "auth_time": 1580063945,
//     "user_id": "W0IturDwy4TYTmX6ilkd2ZbAXRp2",
//     "sub": "W0IturDwy4TYTmX6ilkd2ZbAXRp2",
//     "iat": 1580063945,
//     "exp": 1580067545,
//     "email": "jane@doe.tld",
//     "email_verified": true,
//     "phone_number": "+1234567890",
//     "firebase": {
//         "identities": {
//             "phone": [
//                 "+1234567890"
//             ],
//             "email": [
//                 "jane@doe.tld"
//             ]
//         },
//         "sign_in_provider": "custom"
//     }
// }

echo $token->toString();
// eyJhb...

$tokenString = (string) $token; // string
// eyJhb...

Tenant Awareness

You can create custom tokens that are scoped to a given tenant:

<?php

use Kreait\Firebase\JWT\CustomTokenGenerator;

$generator = CustomTokenGenerator::withClientEmailAndPrivateKey('...', '...');

$tenantAwareGenerator = $generator->withTenantId('my-tenant-id');

Similarly, you can verify that ID tokens were issued in the scope of a given tenant:

<?php

use Kreait\Firebase\JWT\IdTokenVerifier;

$verifier = IdTokenVerifier::createWithProjectId('my-project-id');

$tenantAwareVerifier = $verifier->withExpectedTenantId('my-tenant-id');

Session cookies currently don't support tenants.

Advanced usage

Cache results from the Google Secure Token Store

In order to verify ID tokens, the verifier makes a call to fetch Firebase's currently available public keys. The keys are cached in memory by default.

If you want to cache the public keys more effectively, you can initialize the verifier with an implementation of psr/simple-cache or psr/cache to reduce the amount of HTTP requests to Google's servers.

Here's an example using the Symfony Cache Component:

use Kreait\Firebase\JWT\IdTokenVerifier;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;

$cache = new FilesystemAdapter();

$verifier = IdTokenVerifier::createWithProjectIdAndCache($projectId, $cache);

Supported Versions

Only the latest version is actively supported.

Earlier versions will receive security fixes as long as their lowest PHP requirement receives security fixes. For example, when a version supports PHP 7.4 and PHP 8.0, security support will end when security support for PHP 7.4 ends.

Version Initial Release Supported PHP Versions Status
5.x 25 Nov 2023 ~8.1.0, ~8.2.0, ~8.3.0, ~8.4.0, ~8.5.0 Active
4.x 26 Nov 2022 ~8.1.0, ~8.2.0, ~8.3.0 End of life
3.x 25 Apr 2022 ^7.4, ^8.0 End of life
2.x 03 Jan 2022 ^7.4, ^8.0 End of life
1.x 06 Feb 2017 >=5.5 End of life

License

The MIT License (MIT). Please see License File for more information.

kreait/firebase-tokens 适用场景与选型建议

kreait/firebase-tokens 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 45.57M 次下载、GitHub Stars 达 239, 最近一次更新时间为 2017 年 02 月 05 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「Authentication」 「google」 「auth」 「token」 「firebase」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 kreait/firebase-tokens 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 kreait/firebase-tokens 我们能提供哪些服务?
定制开发 / 二次开发

基于 kreait/firebase-tokens 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 45.57M
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 240
  • 点击次数: 24
  • 依赖项目数: 16
  • 推荐数: 0

GitHub 信息

  • Stars: 239
  • Watchers: 3
  • Forks: 34
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2017-02-05