Muneeb Zulfiqar
Muneeb Zulfiqar

Reputation: 1023

Firebase Create Custom Token on php always returns null on php

Hi I am using cakephp as backend and want to generate a custom token for my website which will be used on my client side. Below is my code to generate a custom code

   $activatedOfferwall = $session->read('ActiveOfferwall'); // 0209341c-da14-46b9-b3c9-8410472e13d2
    $factory = (new Factory)->withServiceAccount(\App\Model\Constants\FirebaseConstants::JSON_FILE)->withDatabaseUri(\App\Model\Constants\FirebaseConstants::DEFAULT_URL);
    $auth = $factory->createAuth();
    $customToken = $auth->createCustomToken($activatedOfferwall['UserHash']);
    Log::debug(json_encode($customToken));

and the fire base rules are

enter image description here

but this always returns an empty json. What am I missing here?

Upvotes: 1

Views: 562

Answers (2)

Manas
Manas

Reputation: 3330

it's not only about the rules. if you are using the package kreait/laravel-firebase (https://firebase-php.readthedocs.io/en/stable/overview.html)

you will have to get the token with it's own method like this:

$firebaseCustomToken = $firebaseAuth->createCustomToken($user->id);
$CustomToken = $firebaseCustomToken->toString(); // like this will return the customToken

hope this helps someone Reference of the git change here: https://github.com/kreait/firebase-php/commit/8b45c07d922364ba9298fa07cbe7ea676c1d05f4

Upvotes: 1

Muneeb Zulfiqar
Muneeb Zulfiqar

Reputation: 1023

For someone who is looking, I found the solution. Rules had to be enter image description here

$generator = CustomTokenGenerator::withClientEmailAndPrivateKey(
            $email,
            $privateKey
        );
        $token = $generator->createCustomToken('[email protected]');

and then send the token on the client side

firebase.auth().signInWithCustomToken(usertoken)
            .then((userCredential) => {
                // Signed in
                var user = userCredential.user;
                firebase.auth().currentUser.getIdToken( /* forceRefresh */ true).then(function(idToken) {
                    console.log(idToken)
                }).catch(function(error) {
                    // Handle error
                });
            })
            .catch((error) => {
                var errorCode = error.code;
                var errorMessage = error.message;
                console.log(error);
                // ...
            });

Upvotes: 1

Related Questions