Pierre Fischer
Pierre Fischer

Reputation: 261

Verify Firebase ID Token with Firebase-PHP

I am using Firebase-Auth to authorize an user on my web-app coded in PHP. The Authorization itself is made with Javascript, which is executet on an Ajax-Request to verify, that an user is logged in.

To use the Firebase-Admin at the server I have implemented Firebase-PHP.

On every AJX-Request I now get the logged in user ID and the ID Token, which I want to verify in PHP like it's been written here in the Docs.

The verification itself works fine. If the token exists I get an "IDToken"-Object. But how can I get the userID out of that object again to verify, that the token is the right one to that user?

$idTokenString = '...';

try {
    $verifiedIdToken = $firebase->getAuth()->verifyIdToken($idTokenString);
    // This is the Token-Object where I cant't find the uid-get-Function
} catch (InvalidIdToken $e) {
    echo $e->getMessage();
}

I couldn't find a method in the documentation or in the classes I searched.

Upvotes: 4

Views: 3917

Answers (1)

jeromegamez
jeromegamez

Reputation: 3551

Maintainer of the library here - the documentation was indeed missing that information, but it is now included and the whole page has been overhauled:

https://firebase-php.readthedocs.io/en/latest/authentication.html#verify-a-firebase-id-token

You can retrieve the UID from the sub claim of the ID token:

try {
    $verifiedIdToken = $firebase->getAuth()->verifyIdToken($idToken);
} catch (InvalidToken $e) {
    echo $e->getMessage();
}
    
$uid = $verifiedIdToken->getClaim('sub'); // lcobucci/jwt:^3.0
// or 
$uid = $verifiedIdToken->claims()->get('sub'); // lcobucci/jwt:^4.0

$user = $firebase->getAuth()->getUser($uid);

Upvotes: 6

Related Questions