3

I am trying to generated the client secret and verify it using Firebase/php-jwt in php for apple sign.

      // generate the client secret
      payload = array(
          "iss" => $teamId,
          'aud' => 'https://appleid.apple.com',
          'iat' => time(),
          'exp' => time() + 3600,
          'sub' => $clientId
      );
      $keycontent = file_get_contents($uri);
      
      $jwt = JWT::encode($payload, $keycontent, 'ES256', $key);

      //Decode the jwt token 
      $decoded = JWT::decode($jwt, $rsa->getPublicKey(), array('ES256'));

getting the public key from the apple (https://appleid.apple.com/auth/keys)

I am getting Signature Verification Failed while executing the code.

This is how I am getting the apple public keys

  $cURLConnection = curl_init();

  curl_setopt($cURLConnection, CURLOPT_URL, 'https://appleid.apple.com/auth/keys');
  curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);

  $publickeys = curl_exec($cURLConnection);
  curl_close($cURLConnection);

  $jsonArrayResponse = json_decode($publickeys);

  foreach ($jsonArrayResponse->keys as $publicKey => $publicValue) {
    if ($publicValue->kid == $d_keys->kid) {
      $rsa = new RSA();
      $rsa->loadKey([
        'e' => new BigInteger(base64_decode($publicValue->e), 256),
        'n' => new BigInteger(base64_decode($publicValue->n), 256)
      ]);
      $decoded = JWT::decode($clientSecretToken, $rsa->getPublicKey(), array('ES256'));
    }
   }
2
  • Just to clarify, your $keycontent is your key created on the Apple Dev Portal, and your $key is the keyID associated with that key?
    – Merricat
    Aug 15, 2020 at 17:19
  • @Merricat yes $keycontent -> private key provided by the apple and $key -> key id
    – Helen
    Aug 16, 2020 at 12:23

2 Answers 2

13

The problem is that you're mixing up parts of the sign-in flow. You're confusing your own client_secret creation with Apple's id_token verification. What you want to do is this:

  1. Receive the Apple's id_token (JWT) and authorization_code from client application
  2. Decode the id_token's header so you can grab the kid (used to verify the signature)
$header_base_64 = explode('.', $id_token)[0];
$kid = (JWT::jsonDecode(JWT::urlsafeB64Decode($header_base_64)))->kid;
  1. Verify the id_token's signature using Apple's public keys (GET https://appleid.apple.com/auth/keys) and the RS256 algorithm. These are in JWK format, so you're expected to build the keys yourself, using the kid you just extracted from the id_token
$public_key = (JWK::parseKeySet($apple_jwk_keys))[$kid]; 
$parsed_id_token = JWT::decode($id_token, $public_key, ['RS256']);
  1. If this all went well, you now know your user sent you a valid Apple id_token, and you can extract the fieelds you need, like userId and email, i.e. $user_id = $parsed_id_token['sub']

  2. Next step would be to exchange your authorization_code for a refresh_token, so you will be able to verify the user up to once a day. First thing you create your client_secret, a JWT that has all the fields you already created. Then you sign this with your own Key + KeyID (created on the Apple dev portal), this time using the ES256 algorithm. The code is the same you already have:

payload = array(
 "iss" => $teamId,
 'aud' => 'https://appleid.apple.com',
 'iat' => time(),
 'exp' => time() + 3600,
 'sub' => $clientId
);

$keycontent = file_get_contents($uri);      
$client_secret = JWT::encode($payload, $keycontent, 'ES256', $key);
  1. Now you send your authorization_code to Apple. (Note that your client_id is your app identifier if your id_token is generated by an iOS app. If it's from a web client, then you need to create a dedicated Service ID)
//1. build POST data
$post_data = [
  'client_id' => $clientId,
  'grant_type' => 'authorization_code',
  'code' => $client_authorization_code,
  'client_secret' => $client_secret
];

//2. create and send request
$ch = curl_init("https://appleid.apple.com/auth/token");
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
   'Accept: application/x-www-form-urlencoded',
   'User-Agent: curl',  //Apple requires a user agent header at the token endpoint
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
$curl_response = curl_exec($ch);
curl_close($ch);

//3. extract JSON from Apple token response
$data = json_decode($curl_response, true);
$refresh_token = $data['refresh_token'];

Now you can save this refresh_token on your database for this specific userId. This way you can verify the user authenticity up to every 24 hours. All you're going to have to do is repeat step #6 with a refresh_token instead of the authorization_code, changing the grant_type too (and remember that this time Apple won't give you a new refresh_token).

That's it! You had no need to verify the signature of your own client_secret, you created it! Apple is the one that needs to do that, let them handle that.

12
  • I was using .p8 format before then changed to .pem format. Still facing the same issue. when i tried to verify the JWT in the jwt.io, it is always throwing "Invalid Signature"
    – Helen
    Aug 16, 2020 at 12:19
  • Yes, I am getting the response for the [appleid.apple.com/auth/token]. After this i get the public key using [appleid.apple.com/auth/keys]. Signature verification issue coming on the line $decoded = JWT::decode($clientSecretToken, $rsa->getPublicKey(), array('ES256'));
    – Helen
    Aug 16, 2020 at 16:42
  • My guess is that your JWT is fine, you're having a problem with verifying its signature with Apple's public key. I'm almost certain you're not creating them correctly, which is why I suggested just trying directly with a POST request to Apple's /auth/token endpoint. For instance, you have not explained what $rsa->getPublicKey() is. You could be doing all sorts of wrong things there lol
    – Merricat
    Aug 16, 2020 at 16:43
  • Is the Apple response valid from appleid.apple.com/auth/token? We should move this to a chat [chat.stackoverflow.com/rooms/219913/…
    – Merricat
    Aug 16, 2020 at 16:45
  • Am unable to use that chat room. I have edited my question
    – Helen
    Aug 16, 2020 at 16:57
2

Here is a complete example of using Sign In With Apple with HTML, Javascript and PHP.

I use jQuery and PHP-JWT from https://github.com/firebase/php-jwt

First create your IDs and keys from the Apple developer portal. These resources will help you get those https://developer.okta.com/blog/2019/06/04/what-the-heck-is-sign-in-with-apple https://sarunw.com/posts/sign-in-with-apple-4/

The sign in works in 2 stages, firstly the client clicks a "Sign In With Apple" button and authenticates with Apple. This returns two pieces of information to our Javascript that we can then post to Apple's servers to verify the client and get their information using PHP.

In this example we use Javascript/PHP to handle the sign in process. The response from Apple is processed using Javascript/PHP and not through the redirect URL. The redirect URL is never called.

The HTML/JS Client side:

<div id="appleid-signin"  data-color="white" data-border="true" data-type="sign in" data-height="40" data-width="200" style="margin-top: 18px; cursor: pointer;"></div>
     <script type="text/javascript" src="https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/en_US/appleid.auth.js"></script>
     <script type="text/javascript">
     jQuery(document).ready(function(){

        AppleID.auth.init({
            clientId : "YOUR.CLIENT.ID",
            scope : "name email",
            redirectURI : "YOUR://REDIRECT/URI",
            usePopup : true
        });
 });
    
    
    document.addEventListener("AppleIDSignInOnSuccess", (data) => {
        //handle successful response
        
        console.log(data);
        
        var appleToken = data.detail.authorization.id_token ;
        var appleCode = data.detail.authorization.code ;
        console.log("Token: "+appleToken);
        console.log("Code: "+appleCode);

        jQuery.ajax({url: "verifyToken.php?authCode="+appleCode+"&idToken="+appleToken, success: function(result){
                var appleUser = JSON.parse(result);
                console.log(appleUser);
                console.log("Customer Email: " + appleUser.email);
        }});
    });
    
    </script>

The above code consists of the HTML Div that contains the sign in with Apple button and the sign in with Apple javascript hosted by Apple.

I use jQuery to call the AppleID.auth.init function after the page has loaded to ensure the JS hosted by Apple is loaded before we try calling its functions.

After the user successfully authenticates with Apple, the response from Apple is processed and we post this off to our PHP script to verify the information with Apple and retrieve the customers information. The PHP returns the customer information from Apple, and in this example it writes this to the web browser console, followed by the customers email address.

Here is the PHP that processes this (verifyToken.php). Replace the variables at the top and upload your private key (preferably somewhere secure). I've added descriptions on where to find the information for the vailables :

<?php

// Requires https://github.com/firebase/php-jwt
// Install with: composer require firebase/php-jwt

$id_token = $_REQUEST['idToken']; // Provided after user completed sign in. In authorisation->id_token
$client_authorization_code = $_REQUEST['authCode']; // Provided after user completed sign in. In authorisation->code
$teamId = "01ABC23D4E" ; // Your Team ID from https://developer.apple.com/account/#/membership/
$clientId = "YOUR.CLIENT.ID" ; // Your sing in with apple identifier from https://developer.apple.com/account/resources/identifiers/list
$privKey = file_get_contents("AppleSignIn_AuthKey.p8"); // Provided by Apple only once after you generate a key at https://developer.apple.com/account/resources/authkeys/list
$keyID = "1A2BCD3EFG" ; // The ID for your key from https://developer.apple.com/account/resources/authkeys/list

require __DIR__ . '/vendor/autoload.php';
use \Firebase\JWT\JWT;
use \Firebase\JWT\JWK;  

$apple_jwk_keys = json_decode(file_get_contents("https://appleid.apple.com/auth/keys"), null, 512, JSON_OBJECT_AS_ARRAY) ;
$keys = array() ;
foreach($apple_jwk_keys->keys as $key)
    $keys[] = (array)$key ;
$jwks = ['keys' => $keys];

$header_base_64 = explode('.', $id_token)[0];
$kid = JWT::jsonDecode(JWT::urlsafeB64Decode($header_base_64));
$kid = $kid->kid;

$public_key = JWK::parseKeySet($jwks);
$public_key = $public_key[$kid]; 

$payload = array(
 "iss" => $teamId,
 'aud' => 'https://appleid.apple.com',
 'iat' => time(),
 'exp' => time() + 3600,
 'sub' => $clientId
);

$client_secret = JWT::encode($payload, $privKey, 'ES256', $keyID);

$post_data = [
  'client_id' => $clientId,
  'grant_type' => 'authorization_code',
  'code' => $client_authorization_code,
  'client_secret' => $client_secret
];

$ch = curl_init("https://appleid.apple.com/auth/token");
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
   'Accept: application/x-www-form-urlencoded',
   'User-Agent: curl',  //Apple requires a user agent header at the token endpoint
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
$curl_response = curl_exec($ch);
curl_close($ch);

$data = json_decode($curl_response, true);
$refresh_token = $data['refresh_token'];

$claims = explode('.', $data['id_token'])[1];
$claims = json_decode(base64_decode($claims));

echo json_encode($claims);

This PHP uses the information returned from Apple in the previous Javascript to verify the information with Apple. It returns the information from Apple back to the Javascript.

The information it returns is as follows:

(
    [iss] => https://appleid.apple.com
    [aud] => YOUR.CLIENT.ID
    [exp] => 1614170648
    [iat] => 1614084248
    [sub] => XXXXX.XXXXX.XXXXX
    [at_hash] => XXXXXX
    [email] => customers@email.address
    [email_verified] => true
    [auth_time] => 1614084210
    [nonce_supported] => 1
)

The process is complete, use this information as you require to create/login a user.

If you are using Sign In with Apple on iOS/macOS then you can use the "sub" to lookup the user, as this is the same as the same as is returned by this:

    ASAuthorizationAppleIDCredential *appleIDCredential = authorization.credential;
    NSString *user = appleIDCredential.user;
3
  • This is very good. One question: the part where it is getting the keys from Apple to build a public key to get a parsed_id_token which never gets used, can be skipped? Mar 2, 2021 at 10:06
  • @Mirko Good spot! It can be skipped and I've removed it from the example.
    – A.Badger
    Mar 3, 2021 at 10:18
  • $public_key is never used. I think it shuld be used to validate id_token, to prevent csrf. Or all of this code from line 17 to 29 can be deleted.
    – El'
    Nov 8, 2022 at 3:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.