phpsign-in-with-apple

Manage Sign with Apple redirect in PHP


I'm trying to implement Sign In with Apple workflow on a backend server, for all those devices that do not support it natively.

I've tried both with and without 3rd party libraries. Right now I'm using patrickbussmann/oauth2-apple.

I successfully authorize the account through the authorization URL, but the redirect URL have no fields (especially the 'code' one). This is how I generate the authorization URL:

function get_apple_signin_url() {
    $options = [
        'scope' => ['email'],
    ];
    $authUrl = $this->provider->getAuthorizationUrl($options);
    $_SESSION['oauth2state'] = $this->provider->getState();
    return '{"url": "'.$authUrl.'"}';
}

The URL obtained is correct and it works utill the end of login: https://appleid.apple.com/auth/authorize?scope=email&state=a9583c14408af68ac05cbfed3a8274ef&response_type=code&approval_prompt=auto&redirect_uri=MY_REDIRECT_URI&client_id=MY_CLIENT_ID&response_mode=form_post

This is the code inside the redirect uri (apple_auth_redirect.php):

<?php

if (isset($_POST['code'])) {
    $code = urlencode($_POST['code']);
    header("Location: intent://callback?apple_id_token=".$code);
} else {
    echo "no_code";
}

As you can see from the authorization URL, the response_mode is form_post. If I use query as response_mode I obtain the code, but I cannot insert email as scope. More details in response_mode at Incorporating Sign in with Apple into Other Platforms (developer.apple.com).

This is the current authorization workflow I've implemented:

  1. Mobile app calls get_apple_signin_url on the server.
  2. Mobile app opens the url in the browser.
  3. The authorization through Apple website is completed and the browser is redirected to redirect uri apple_auth_redirect.php.
  4. The code should be parsed by apple_auth_redirect.php but the redirect request has no fields.

I've implemented the same procedure for Google and Huawei sign in without problems.


Solution

  • I solved the problem. I thought that I wasn't correctly handling the redirect. However, the problem was that I wrote redirect_uri=MY_REDIRECT_URI without "www", just the domain e.g., "my_domain.com". With "www" e.g., "www.my_domain.com", it worked.