1

I am creating JWT using documentation mentioned here.

Everything is done as mentioned in the documentation.

Here is the code snippet.

When I am returning this token to android client, Android client throws following error.

com.google.android.gms.tasks.RuntimeExecutionException: com.google.firebase.auth.FirebaseAuthInvalidCredentialsException: The custom token format is incorrect. Please check the documentation.

I am not sure, what am I missing while creating token.

$service_account_email = "abc-123@a-b-c-123.iam.gserviceaccount.com";
            $private_key = "-----BEGIN PRIVATE KEY-----VERY LONG KEY-----END PRIVATE KEY-----\n";//See github link for key if needed

            $now_seconds = time();
            $payload = array(
              "iss" => $service_account_email,
              "sub" => $service_account_email,
              "aud" => "https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",
              "iat" => $now_seconds,
              "exp" => $now_seconds+(60*60),  // Maximum expiration time is one hour
              "uid" => $mobile
            );
            $token = JWT::encode($payload, $private_key, "HS256");

Here is the screenshot of extracted token using jwt.io enter image description here

Amol Chakane
  • 1,501
  • 2
  • 21
  • 43

1 Answers1

0

I was also facing a similar issue when I was simply trying to run the Example with RS256 (openssl) from firebase/php-jwt Readme File.

I posted a question about the same here.

and based on the Answer and comments, I learned that the Private and Public keys in the example are incorrect.

I generated new key pair using the following commands (copied from this Gist, the other options did not work when I tried.)

Private Key

openssl genrsa -out private.pem 2048

Public Key

openssl rsa -in private.pem -pubout -out public.pem

and I used those files in my code and now it's working fine and even getting verified on jwt.io

Here is the complete code:

<?php

include '../vendor/autoload.php';

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

$privateKey = file_get_contents(__DIR__ . '/private.pem');

$publicKey = file_get_contents(__DIR__ . '/public.pem');

$payload = [
    'iss' => 'example.org',
    'aud' => 'example.com',
    'iat' => 1356999524,
    'nbf' => 1357000000,
];

$jwt = JWT::encode($payload, $privateKey, 'RS256');
echo "Encode:\n" . print_r($jwt, true) . "<br/><br/>";

$decoded = JWT::decode($jwt, new Key($publicKey, 'RS256'));

/*
NOTE: This will now be an object instead of an associative array. To get
an associative array, you will need to cast it as such:
 */

$decoded_array = (array) $decoded;
echo "Decode:\n" . print_r($decoded_array, true) . "\n";

Screenshot from jwt.io: enter image description here

Hope this helps.

Best.

Akshay Khale
  • 8,151
  • 8
  • 50
  • 58