【发布时间】:2016-10-26 11:10:03
【问题描述】:
我正在尝试从使用 PHP、Google Auth library 和用于 Firebase REST 的 wrapper 的服务器访问 Firebase...这非常适合实现这一目标:
use Firebase\JWT\JWT;
use Google\Auth\Credentials\ServiceAccountCredentials;
use Google\Auth\HttpHandler\HttpHandlerFactory;
use GuzzleHttp\Client;
$email = 'account@email.com';
$key = 'private_key_goes_here';
$scopes = [
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/firebase.database',
];
$creds = [
'client_email' => $email,
'private_key' => $key,
];
$serviceAccount = new ServiceAccountCredentials($scopes, $creds);
$handler = HttpHandlerFactory::build(new Client());
$token = $serviceAccount->fetchAuthToken($handler);
$firebase = new \Firebase\FirebaseLib($url, $token);
$value = $firebase->get('test/hello');
# $value now stores "world"
但是,这需要 Firebase 中的安全规则是通用读/写,这是我不想要的。如果我将我的安全规则更新为:
{
"rules": {
"test": {
".read": "auth != null"
}
}
}
$value 中的结果变为{"error": "Permission denied"}。我进行了广泛的搜索,并尝试了许多排列和可能的解决方案,但没有确凿的结果。
我已经使用this code 向最终客户端提供 JWT 令牌,它们可以成功使用它们并毫无问题地利用安全规则。我最初为服务器尝试了相同的方法,但没有成功。我选择尝试结合这两种方法:
# Snipping code that didn't change...
$serviceAccount = new ServiceAccountCredentials($scopes, $creds);
$handler = HttpHandlerFactory::build(new Client());
$payload = [
'iss' => $email,
'sub' => $email,
'aud' => 'https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit',
'iat' => time(),
'exp' => time() + 60 * 60,
'uid' => '123',
'claims' => [
'uid' => '123',
],
];
$payload = $serviceAccount->updateMetadata($payload);
$token = JWT::encode($payload, $key, 'RS256');
$firebase = new \Firebase\FirebaseLib($url, $token);
$value = $firebase->get('test/hello');
这似乎接近了,但$value 现在包含{"error": "Missing claim 'kid' in auth header."}。为了解决这个问题,我修改了编码调用:
$token = JWT::encode($payload, $key, 'RS256', 'key_id_goes_here');
这会导致稍有不同的错误:Invalid claim 'kid' in auth header.,表明我在正确的轨道上......但并不完全在那里。直接使用 JWT 令牌会产生完全相同的结果。任何想法我做错了什么?电子邮件、私钥和密钥 ID 都直接来自我创建服务帐户时提供的 json 凭据文件。
我查看了几十页的文档和帖子,以下是最有帮助的:
【问题讨论】:
标签: php rest firebase firebase-realtime-database firebase-authentication