Sun*_*thi 0 php firebase-authentication firebase-realtime-database
我正在使用 Firebase Auth Rest API。我有用 PHP 编写的代码来将用户添加到数据库和 firebase 身份验证。我存储的信息是kind、idToken、email、refreshToken、expiresIn、localId。这一切都很棒!
现在,当我尝试从数据库中删除用户时,它工作正常,但不会从 firebase 身份验证中删除用户。请在下面找到用于注册和删除用户的代码。
我得到的错误是 CREDENTIALS_TOO_OLD_LOGIN_AGAIN(或)INVALID_ID_TOKEN。
FIREBASE_KEY 是我的 firebase 密钥,在 $data 我传递用户 idToken
/*
* User Sign Up
*/
function user_signup($data){
$response = true;
$data = json_encode($data);
$url = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/signupNewUser?key=".FIREBASE_KEY;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$jsonResponse = curl_exec($ch);
if(curl_errno($ch))
{
$response = false;
}
curl_close($ch);
return $jsonResponse;
}
/*
* User Delete
*/
/* function user_delete($data){
$response = true;
$data = json_encode($data);
$url = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/deleteAccount?key=".FIREBASE_KEY;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$jsonResponse = curl_exec($ch);
if(curl_errno($ch))
{
$response = false;
}
curl_close($ch);
return $jsonResponse;
} */
Run Code Online (Sandbox Code Playgroud)
与 Firebase REST API 交互的方式有两种:
要删除用户,您可以使用这两种方法,但是在使用用户的 ID 令牌时,您必须以用户身份进行身份验证(有效地模拟他们),然后才能代表该用户执行任何操作。
更好的解决方案是使用 Admin SDK 来执行该任务。如将 Firebase Admin SDK 添加到您的服务器 中所述,通过使用服务帐户凭据对您对 Firebase REST API 的请求进行身份验证,您将能够更轻松地执行管理任务(例如从身份验证数据库中删除用户)。
以下是开始使用基于服务帐户的身份验证的步骤:
$client->post('https://www.googleapis.com/identitytoolkit/v3/relyingparty/deleteAccount', [
'json' => [
'localId' => 'uid-of-user-to-delete'
]
]);
Run Code Online (Sandbox Code Playgroud)
该localId参数未记录在https://firebase.google.com/docs/reference/rest/auth/#section-delete-account 上,但它在官方管理 SDK 中使用并且有效。
使用 Admin SDK ( https://firebase.google.com/docs/admin/setup#initialize_the_sdk ) 将是执行此类管理任务的推荐方式。Node.js、Java、Python、Go 和 C# 都有官方 SDK - 我为 PHP 维护了一个非官方 SDK,你可以在https://github.com/kreait/firebase-php找到。有了它,您可以像这样执行相同的任务:
// kreait/firebase-php ^5.0
$factory = (new Factory)->withServiceAccount('service_account.json');
$auth = $factory->createAuth();
$auth->deleteUser('uid-of-user-to-delete');
// kreait/firebase-php ^4.0
$serviceAccount = ServiceAccount::fromJsonFile('service_account.json');
$firebase = (new Factory())
->withServiceAccount($serviceAccount)
->create();
$firebase->getAuth()->deleteUser('uid-of-user-to-delete');
Run Code Online (Sandbox Code Playgroud)
旁注:
我会考虑将用户的 ID 令牌存储在单独的数据库中存在安全风险:如果您的数据库遭到破坏,攻击者可以获得对您用户的 ID 令牌的访问权,并可以使用尚未过期的那些令牌来访问您的应用程序。
将用户从前端(Web、移动)传递到后端(服务器)的推荐流程是:
| 归档时间: |
|
| 查看次数: |
1766 次 |
| 最近记录: |