Skip to content

Instantly share code, notes, and snippets.

@mingalevme
Last active September 15, 2022 10:01
Show Gist options
  • Select an option

  • Save mingalevme/c6fca8df82b40e5b60a009dc4b754e67 to your computer and use it in GitHub Desktop.

Select an option

Save mingalevme/c6fca8df82b40e5b60a009dc4b754e67 to your computer and use it in GitHub Desktop.
Example of Generating Apple SignIn Access Token (based on Laravel/Lumen Command)
<?php
declare(strict_types=1);
namespace App\Console\Commands\Apple;
use App\Console\Command;
use App\Helpers\Jwt;
use GuzzleHttp\ClientInterface as GuzzleClient;
class GenerateAccessToken extends Command
{
protected $signature = 'apple:sing-in:token {code}';
public function handle(GuzzleClient $guzzle): int
{
//
// DO NOT STORE APPLE SIGN IN CREDENTIALS IN THE CODE, THIS IS AN EXAMPLE
//
$kid = ''; // SignIn Key ID
$privateKey = ' // SignIn Key
-----BEGIN PRIVATE KEY-----
...
-----END PRIVATE KEY-----';
$iss = ''; // Developer ID
$aud = 'https://appleid.apple.com';
$sub = ''; // mobile app id
$iat = time();
$exp = $iat + 86400*30; // access token expiration timeout
$redirectUrl = 'https://example/apple/callback';
$code = $this->argument('code');
$clientSecret = (string) Jwt::issue($privateKey, $kid, $iss, $aud, $sub, $iat, $exp);
$response = $guzzle->request('POST', 'https://appleid.apple.com/auth/token', [
'form_params' => [
'client_id' => $sub,
'code' => $code,
'client_secret' => $clientSecret,
'grant_type' => 'authorization_code',
'redirect_uri' => $redirectUrl,
],
]);
$this->line($response->getBody()->getContents());
return 0;
}
}
<?php
declare(strict_types=1);
namespace App\Helpers;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Ecdsa\Sha256;
use Lcobucci\JWT\Signer\Key;
use Lcobucci\JWT\Token;
class Jwt
{
public static function issue(string $privateKey, string $kid, string $iss, string $aud, string $sub, int $iat, int $exp): Token
{
$signer = new Sha256();
return (new Builder())
->issuedBy($iss)
->permittedFor($aud)
->relatedTo($sub)
->issuedAt($iat)
->expiresAt($exp)
->withHeader('kid', $kid)
->withHeader('alg', 'ES256')
->withHeader('type', 'JWT')
->getToken($signer, new Key($privateKey));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment