I have a PHP application and I am trying to generate a token to authenticate users so that they can access Firebase from the browser.
I have generated a private key from service account in Firebase console and I use the firebase/php-jwt library. When trying to access with the signInWithCustomToken
method from javascript I always get the error>
The custom token format is incorrect. Please see the documentation
The code with which I generate the token is:
use Firebase\JWT\JWT;
require_once("php-jwt-master/src/JWT.php");
$service_account_email = "firebase-adminsdk-ierut@......iam.gserviceaccount.com"; // Dots are app name
$key = "-----BEGIN PRIVATE KEY-----\n..........\n-----END PRIVATE KEY-----\n"; // Dots are private key from the downloaded file
$time = time();
$token = array( 'iat' => $time,
'exp' => $time + 3000,
'uid' => '1',
'aud' => 'https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit',
'iss' => $service_account_email,
'sub' => $service_account_email
);
$jwt = JWT::encode($token, $key, 'HS256');
The javascript code is:
function login(){
var token = document.getElementById("token").value;
firebase.auth().signInWithCustomToken(token)
.then((user) => {
console.log("Autenticado");
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorCode + " - " + errorMessage);
});
}
I have checked the jwt with jwt.io tool and it seems to be correct.
I am not sure in the key format, I have tried with the header and the "\ n" in a single line as in the file and also without the "\ n" and using the returns in a multiline variable with "<<<".
I have also tried using the encode function with or without the parameter 'HS256'. But I always get the same error.
Thanks in advance for any response.