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;
$keycontent
is your key created on the Apple Dev Portal, and your$key
is the keyID associated with that key?