乐闻世界logo
搜索文章和话题

How to verify firebase ID token with PHP( JWT )?

1个答案

1

When using PHP to handle Firebase ID tokens (JWT, i.e., JSON Web Tokens), the primary steps involve verifying the token's validity to ensure it is issued by Firebase and has not been tampered with. This process typically includes the following steps:

1. Retrieve Firebase Public Keys

Firebase uses a pair of public and private keys to issue and verify JWTs. Public keys are public and can be used to verify the JWT's signature. First, you need to retrieve these public keys from Firebase's public key server.

php
function fetchFirebasePublicKey() { $url = 'https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($ch); curl_close($ch); $keys = json_decode($output, true); return $keys; }

2. Parse and Verify JWT

Once you have the public key, you can use it to verify the JWT's signature and check the token's validity, such as the correct issuer (iss) and appropriate audience (aud).

Here, it is recommended to use a third-party library, such as firebase/php-jwt, to help parse and verify JWTs. First, you need to install this library:

bash
composer require firebase/php-jwt
php
use \Firebase\JWT\JWT; use \Firebase\JWT\Key; function verifyFirebaseToken($idToken) { $publicKeys = fetchFirebasePublicKey(); $decodedToken = null; foreach ($publicKeys as $kid => $publicKey) { try { $decodedToken = JWT::decode($idToken, new Key($publicKey, 'RS256')); if ($decodedToken->iss !== 'https://securetoken.google.com/YOUR_PROJECT_ID' || $decodedToken->aud !== 'YOUR_PROJECT_ID') { throw new Exception('Invalid token'); } // Token is valid return $decodedToken; } catch (Exception $e) { // Continue if the iteration fails, might be due to wrong key continue; } } throw new Exception('Token could not be verified.'); }

3. Use the Retrieved User Information

If the JWT verification is successful, $decodedToken will contain user-related information, such as the user's UID ($decodedToken->uid), which you can use for user identity confirmation or other logical processing.

php
$userId = $decodedToken->uid; // Perform database queries or other operations

By following these steps, you can effectively verify Firebase ID tokens in a PHP environment, ensuring that only legitimate requests from Firebase are accepted. This is crucial for protecting your application and user data security.

2024年8月16日 00:11 回复

你的答案