Skip to content

Instantly share code, notes, and snippets.

@patrickbussmann
Created October 17, 2019 23:27
Show Gist options
  • Star 25 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save patrickbussmann/877008231ef082cc5dc4ee5ca661a641 to your computer and use it in GitHub Desktop.
Save patrickbussmann/877008231ef082cc5dc4ee5ca661a641 to your computer and use it in GitHub Desktop.
Sign in with Apple - PHP
<?php
# composer require web-token/jwt-framework
require_once 'vendor/autoload.php';
use Jose\Component\Core\AlgorithmManager;
use Jose\Component\KeyManagement\JWKFactory;
use Jose\Component\Signature\Algorithm\ES256;
use Jose\Component\Signature\JWSBuilder;
use Jose\Component\Signature\Serializer\CompactSerializer;
/** Your team identifier: https://developer.apple.com/account/#/membership/ (Team ID) */
$teamId = '1A234BFK46';
/** The client id of your service: https://developer.apple.com/account/resources/identifiers/list/serviceId */
$clientId = 'org.example.service';
/** Code from request: https://appleid.apple.com/auth/authorize?response_type=code&client_id={$clientId}&scope=email%20name&response_mode=form_post&redirect_uri={$redirectUri} */
$code = 'ab1c23456fb104dbfa034e0e66bc58370.0.nrwxq.yQMut7nanacO82i7OvNoBg';
/** The ID of the key file: https://developer.apple.com/account/resources/authkeys/list (Key ID) */
$keyFileId = '1ABC6523AA';
/** The path of the file which you downloaded from https://developer.apple.com/account/resources/authkeys/list */
$keyFileName = 'AuthKey_1ABC6523AA.p8';
/** The redirect uri of your service which you used in the $code request */
$redirectUri = 'https://example.org';
$algorithmManager = new AlgorithmManager([new ES256()]);
$jwsBuilder = new JWSBuilder($algorithmManager);
$jws = $jwsBuilder
->create()
->withPayload(json_encode([
'iat' => time(),
'exp' => time() + 3600,
'iss' => $teamId,
'aud' => 'https://appleid.apple.com',
'sub' => $clientId
]))
->addSignature(JWKFactory::createFromKeyFile($keyFileName), [
'alg' => 'ES256',
'kid' => $keyFileId
])
->build();
$serializer = new CompactSerializer();
$token = $serializer->serialize($jws, 0);
$data = [
'client_id' => $clientId,
'client_secret' => $token,
'code' => $code,
'grant_type' => 'authorization_code',
'redirect_uri' => $redirectUri
];
$ch = curl_init();
curl_setopt_array ($ch, [
CURLOPT_URL => 'https://appleid.apple.com/auth/token',
CURLOPT_POSTFIELDS => http_build_query($data),
CURLOPT_RETURNTRANSFER => true
]);
$response = curl_exec($ch);
curl_close ($ch);
var_export(json_decode($response, true));
/**
* array (
* 'access_token' => 'ab12cd3ef45db4f86a7d32cbbf7703a45.0.abcde.Ab01C3_D4elgkHOMcFuXpg',
* 'token_type' => 'Bearer',
* 'expires_in' => 3600,
* 'refresh_token' => 'abcdef12345678bb9bbbefba3e36118a2.0.mrwxq.Vo5t5ogmUXFERuNtiMbrvg',
* 'id_token' => 'RS256 Encoded Hash',
* )
*/
@bagardavidyanisntreal
Copy link

does it work?
I made the same by ruby JWT library but the token output is different
Will try this but I'm really not sure if this works

@patrickbussmann
Copy link
Author

The token output must be different all the time 😉
For me it works and you can check the JWT token here, too: https://jwt.io/

When you need help by implementing I can help you via Skype & TeamViewer 👍

@bagardavidyanisntreal
Copy link

@patrickbussmann I agree with you, but check it out

you need to install ruby with gems
in my case on UBUNTU

sudo su ...
apt update && apt install ruby-full
gem install jwt

ruby generator example: the diff is only the last part of the token (first TWO will be the same)

generator.rb

require 'jwt'

key_file = 'AuthKey_KIDHASH.p8'
ecdsa_key = OpenSSL::PKey::EC.new IO.read key_file

headers = {
    'kid' => 'KIDHASH'
}

claims = {
    'iss' => 'ISS',
    
    # let's say that this two values are constants
    'iat' => 1572102587,
    'exp' => 1585235387,

    'aud' => 'https://appleid.apple.com',
    'sub' => 'SERVICEID',
}

token = JWT.encode claims, ecdsa_key, 'ES256', headers

File.open('RUBI_output.txt', 'w') do |fo|
    fo.puts token
end

puts 'done'

to check it ruby generator.rb

and then I've tried the same values with your code example, but result was invalid_client
have no idea what's wrong

BTW thank U for your reply

@GhadaKh97
Copy link

" 'code' => $code,"
Can you explain how to get this code? I try the request but it open a page require apple id :(

@bagardavidyanisntreal
Copy link

bagardavidyanisntreal commented Nov 29, 2019 via email

@patrickbussmann
Copy link
Author

@GhadaKh97: Check out https://github.com/patrickbussmann/oauth2-apple when you want it much easier 😉

@sujeetimpact
Copy link

The token output must be different all the time
For me it works and you can check the JWT token here, too: https://jwt.io/

When you need help by implementing I can help you via Skype & TeamViewer

@patrickbussmann I need your help. I am implementing the same but the response is invalid client_id in token verification. please assist me
Email address sujeet.yadav@impactguru.com

@Shahor
Copy link

Shahor commented Mar 9, 2020

Hi guys,
Any of you found a solution for this?

@dusterio
Copy link

@patrickbussmann hmm, getting 401 invalid_client with your implementation - same as with any other method/library I tried today :( did you have to "verify" your domain with a plain text file? I see some developers refer to doing it, but it doesn't seem to exist anymore in the developer console

@akbayt
Copy link

akbayt commented May 14, 2020

Hi guys,

The same response :( "invalid client_id".

I am using the SIWA in our app and pass the code to the server for token verification. Identity token validation works properly. I assume all private/public key setup is correct. I already set up everything on the apple developer page. My question is, do I supposed to use this on a live system (where the redirect URL points)? does it suppose to work on my local server?

@patrickbussmann
Copy link
Author

Did you followed the guide exactly? @Shahor @dusterio @akbayt

@akbayt
Copy link

akbayt commented May 14, 2020

Hi @patrickbussmann, thanks for your quick answer.

Unfortunately, I couldn't use "web-token/jwt-framework", we don't have "symfony" on our PHP. I used "firebase/php-jwt" for JWT encoding. I validated the generated JWT for client-secret. It looks like it works. Regarding the rest, all the fields are correct (clientId ...) as you explained in the example above.

As I asked in my first question. Should I run this on the live system? or does it supposed to work on my local?

Thanks in advance

Edit:

By the way, our setup is a bit different. I am not getting this code from a web app.

you mentioned that the "code" is from the request to apple:

/** Code from request: https://appleid.apple.com/auth/authorize?response_type=code&client_id={$clientId}&scope=email%20name&response_mode=form_post&redirect_uri={$redirectUri} */
$code = 'ab1c23456fb104dbfa034e0e66bc58370.0.nrwxq.yQMut7nanacO82i7OvNoBg';

In my case, it is from our iOS app. "appleIDCredential.authorizationCode", which I assume the correct value.

@akbayt
Copy link

akbayt commented May 15, 2020

Finally, solved the issue:

First, I had a problem with the JWT header (it was just a typo). When I fixed the issue I started getting "invalid_grant", instead of "invalid_client".

And the solution was using app id instead of service id. Because the authentication code was generated for the app.

I hope this will help others.

@EltechAdmin
Copy link

@patrickbussmann if you can help complete it, would be a great help. I don't get any errors but im seeing different values every time.
tikurlion@gmail.com thanks

@yungyili
Copy link

@patrickbussmann You sample code works fine for me. Thank you. You just saved my day.

@abaron
Copy link

abaron commented Jul 15, 2020

The token's expiration time, in Unix epoch time; tokens that expire more than 20 minutes in the future are not valid (Ex: 1528408800)

@aaron2310
Copy link

Hi Patrick,

We need to generate the code in php language from the below request.

/** Code from request: https://appleid.apple.com/auth/authorize?response_type=code&client_id={$clientId}&scope=email%20name&response_mode=form_post&redirect_uri={$redirectUri} */

Can you please help on this??

@patrickbussmann
Copy link
Author

@aaron2310: Use https://github.com/patrickbussmann/oauth2-apple
And then easily fill out your place holders.
-> {clientId}, {redirectUri}

Or what is your question here?

@EltechAdmin do you still need help? 😊

@aaron2310
Copy link

aaron2310 commented Aug 7, 2020

@aaron2310: Use https://github.com/patrickbussmann/oauth2-apple
And then easily fill out your place holders.
-> {clientId}, {redirectUri}

Or what is your question here?

@EltechAdmin do you still need help? blush

Thanks for the instant response.!!

I need the code which you generated $code = 'ab1c23456fb104dbfa034e0e66bc58370.0.nrwxq.yQMut7nanacO82i7OvNoBg';

I am able to craete the request from this URL https://appleid.apple.com/auth/authorize?response_type=code&client_id={$clientId}&scope=email%20name&response_mode=form_post&redirect_uri={$redirectUri} */

It redirects to the apple sign in page and shows two factor sign in and so on.. But our purpose is to generate the code as like above

Could you please help.. (In php) Hope the link you will help to get the code..Am i right??

@patrickbussmann
Copy link
Author

Ah yes @aaron2310:
You have the URL. When you open it then you are on the apple sign in page.
Now you sign in with Apple.
Then you'll be redirected to {$redirectUri} with query parameters (or POST body) "code". (and on first sign in first name, last name, email and this things)

So when you'll be redirected to your $redirectUri let your browser console with network tab open. Then you can check your POST Body and/or query parameters easily.

👍

@aaron2310
Copy link

Thanks a lot!! will get back if any clarifications

@AaronSolomon23
Copy link

Heyy it works. we changed the request_method from form_state to query. It works.
Is there any other way without using the jwt-framework?? just to know

@diego-lipinski-de-castro

It works but pay attention, the code provided by the client is valid only for a short time, so dont keep testing with the same code for a long time because it will say invalid_grant

@whiledle
Copy link

Patrick, I need your help. How do I decrypt the information in the id_token that the apple server returns?

@rL071
Copy link

rL071 commented Jun 28, 2021

Thank you very much !!!

@gradus0
Copy link

gradus0 commented Oct 2, 2021

Patrick, I need your help. How do I decrypt the information in the id_token that the apple server returns?

https://github.com/gradus0/appleAuth

@ellie-me
Copy link

ellie-me commented Feb 13, 2022

You saved my life! I am implementing the same using Guzzle and all I needed was to use your curl method instead.

@nolimitdev
Copy link

Be careful because of this invalid_client error could be misleading (as always Apple's error messages)

$postParams = array(
    'code' => ...,
    'client_id' => ...,
    'client_secret' => ...,
    'grant_type' => 'authorization_code',
    'redirect_uri' => ...,
);

$curl = curl_init('https://appleid.apple.com/auth/token');

// never pass params as just array for apple without stringifying via http_build_query()
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($postParams));

When you will use just curl_setopt($curl, CURLOPT_POSTFIELDS, $postParams); it is valid POST request but another type than Apple expects but lazy apple developers are not able to provide error that this type of POST request is unsupported.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment