title: Apple Sign In "invalid_client", signing JWT for authentication using PHP and openSSL
body: <p>I'm trying to implement Apple sign in into an Android App using this <a href="https://github.com/willowtreeapps/sign-in-with-apple-button-android" rel="noreferrer">library</a>. The main flow is described in the documentation: the library returns an authorization code on the Android side. This authorization code has to be sent to my backend which, in turn, sends it to the Apple servers in order to get back an access token. </p>
  
  <p>As described <a href="https://developer.okta.com/blog/2019/06/04/what-the-heck-is-sign-in-with-apple" rel="noreferrer">here</a> and <a href="https://medium.com/better-programming/apple-sign-in-custom-servers-and-an-expiry-conundrum-d1ad63223870" rel="noreferrer">here</a>, in order to obtain the access token we need to send to the Apple API a list of parameters, the authorization code and a signed JWT. In particular, JWT needs to be signed with a ES256 algorithm using a private .p8 key which has to be generated and downloaded from the Apple developer portal. <a href="https://developer.apple.com/documentation/signinwithapplerestapi/generate_and_validate_tokens" rel="noreferrer">Apple doc</a></p>
  
  <p>Here is my PHP script:</p>
  
  <pre><code>&lt;?php
  
  $authorization_code = $_POST('auth_code');
  
  $privateKey = &lt;&lt;&lt;EOD
  -----BEGIN PRIVATE KEY-----
  my_private_key_downloaded_from_apple_developer_portal (.p8 format)
  -----END PRIVATE KEY-----
  EOD;
  
  $kid = 'key_id_of_the_private_key'; //Generated in Apple developer Portal
  $iss = 'team_id_of_my_developer_profile';
  $client_id = 'identifier_setted_in_developer_portal'; //Generated in Apple developer Portal
  
  $signed_jwt = $this-&gt;generateJWT($kid, $iss, $client_id, $privateKey);
  
  $data = [
              'client_id' =&gt; $client_id,
              'client_secret' =&gt; $signed_jwt,
              'code' =&gt; $authorization_code,
              'grant_type' =&gt; 'authorization_code'
          ];
  $ch = curl_init();
  
  curl_setopt($ch, CURLOPT_URL, 'https://appleid.apple.com/auth/token');
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  
  $serverOutput = curl_exec($ch);
  
  curl_close ($ch);
  
  var_dump($serverOutput);
  
  function generateJWT($kid, $iss, $sub, $key) {
  
      $header = [
          'alg' =&gt; 'ES256',
          'kid' =&gt; $kid
      ];
      $body = [
          'iss' =&gt; $iss,
          'iat' =&gt; time(),
          'exp' =&gt; time() + 3600,
          'aud' =&gt; 'https://appleid.apple.com',
          'sub' =&gt; $sub
      ];
  
      $privKey = openssl_pkey_get_private($key);
      if (!$privKey) return false;
  
      $payload = $this-&gt;encode(json_encode($header)).'.'.$this-&gt;encode(json_encode($body));
      $signature = '';
      $success = openssl_sign($payload, $signature, $privKey, OPENSSL_ALGO_SHA256);
      if (!$success) return false;
  
      return $payload.'.'.$this-&gt;encode($signature);
  }
  
  function encode($data) {
      $encoded = strtr(base64_encode($data), '+/', '-_');
      return rtrim($encoded, '=');
  }
  
  ?&gt;
  </code></pre>
  
  <p>The problem is that the response from Apple is always:</p>
  
  <pre><code>{"error":"invalid_client"}
  </code></pre>
  
  <p>Reading <a href="https://forums.developer.apple.com/thread/123723" rel="noreferrer">here</a> it seems that the problem could be related to openSSL which generates a signature which is not correct for Apple ("<em>OpenSSL's ES256 signature result is a DER-encoded ASN.1 structure (it's size exceed 64). (not a raw R || S value)</em>").</p>
  
  <p><strong>Is there a way to obtain the correct signature using openSSL?</strong></p>
  
  <p><strong>Is the p8 format the correct input for the openssl_sign and openssl_pkey_get_private functions?</strong>
  (I noticed that the provided .p8 key does not work if used in <a href="https://jwt.io/" rel="noreferrer">jwt.io</a> in order to compute the signed jwt.)</p>
  
  <p>In the openSSL documentation I read that a pem key should be provided, <strong>how can I convert a .p8 in a .pem key?</strong> </p>
  
  <p>I also tried with some PHP libraries which basically use the same steps described above like <a href="https://github.com/firebase/php-jwt" rel="noreferrer">firebase/php-jwt</a> and <a href="https://github.com/lcobucci/jwt" rel="noreferrer">lcobucci/jwt</a> but the Apple response is still "invalid client".</p>
  
  <p>Thank you in advance for your help,</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>I tried to completely remove openSSL from the equation. Using the .pem key generated from the .p8 one I have generated a signed JWT with jwt.io. With this signed JWT the Apple API replies correctly. At this point I'm almost sure it's an openSSL signature problem. The key problem is how to obtain a proper ES256 signature using PHP and openSSL.</p>