Skip to content

Instantly share code, notes, and snippets.

@RiFi2k
Last active June 10, 2018 02:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RiFi2k/56eb01947842d7725b3caed707caa0c0 to your computer and use it in GitHub Desktop.
Save RiFi2k/56eb01947842d7725b3caed707caa0c0 to your computer and use it in GitHub Desktop.
/**
* Generate a signed JWT for Apple Music API
* Need to include this linked composer.json
* https://gist.github.com/RiFi2k/807a8d8de14d34db8455e8440eed528a
*/
use Jose\Component\KeyManagement\JWKFactory;
use Jose\Component\Core\AlgorithmManager;
use Jose\Component\Core\Converter\StandardConverter;
use Jose\Component\Signature\Algorithm\ES256;
use Jose\Component\Signature\JWSBuilder;
use Jose\Component\Signature\Serializer\CompactSerializer;
// Apple Developers Credentials
$path_to_cert = '/path/to/cert/file/cert.p8';
$team_id = 'TEAM_ID_FROM_APPLE';
$key_id = 'KEY_ID_FROM_APPLE';
/**
* Generates a signed JWT with a configurable expiration
* for Apple Music API calls
* param int $expires Number of seconds before JWT expires.
* return string Signed json web token.
*/
function generate_musickit_token( $expires = 1440 ) {
$key = JWKFactory::createFromKeyFile( $path_to_cert );
// This converter wraps json_encode/json_decode with some parameters
$jsonConverter = new StandardConverter();
// This managers handles all algorithms we need to use.
$algorithmManager = AlgorithmManager::create([
new ES256(),
]);
// The JWS Builder
$jwsBuilder = new JWSBuilder( $jsonConverter, $algorithmManager );
$time = time();
// First we have to encode the payload. Now only strings are accepted.
$payload = $jsonConverter->encode([
'iss' => $team_id,
'iat' => $time,
'exp' => $time + (int)$expires,
]);
$headers = [
'alg' => 'ES256',
'kid' => $key_id,
];
// We build our JWS object
$jws = $jwsBuilder
->create()
->withPayload( $payload )
->addSignature( $key, $headers )
->build();
// We need to serialize the token.
// In this example we will use the compact serialization mode (most common mode).
$serializer = new CompactSerializer( $jsonConverter );
$token = $serializer->serialize( $jws );
return $token;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment