javascriptpythonjwtapple-musickit

Creating A Developer Token For Apple Music API


I'm currently trying to create a Developer Token for the MusicKit API, I have the following: 10 digit Team-Id, 10 digit Key-Id, a .p8 AuthKey file. All of these are valid. I have tried using the following code to generate the token:

JavaScript in VSCode:

"use strict";
const fs      = require("fs");
const jwt     = require("jsonwebtoken");

const privateKey = fs.readFileSync("AuthKey.p8").toString();
const teamId     = "ABCDEFGHIJ";
const keyId      = "1234567891";

const jwtToken = jwt.sign({}, privateKey, {
    algorithm: "ES256",
    expiresIn: "180d",
    issuer: teamId,
  header: {
    alg: "ES256",
    kid: keyId
  }
});

console.log(jwtToken);

Python (pelauimagineering's generator code from github with some minor tweaks)

import datetime
import jwt

//not a real private key but it looks something like this
secret = """-----BEGIN PRIVATE KEY-----
asdfg1rty5GSM49AgEGCCqGSM49AwEHBHkwdwIBAQQguWRXMHYkuFImkMGByqEPT
jaXQyO0WK1BjYpuDxIgNQ5nHRRFCuUOi8mgCgYIKoZIzj0DAQehcp0+Z+jwRANCAA
RCBFg8fL08QS36Fb8HmY+eFrDWMO00w5unCo5n8VyLhvttIZeByXlVsJrK/L3f/
F2wYmZme
-----END PRIVATE KEY-----"""
teamId = "ABCDEFGHIJ";
keyId = "1234567891"
alg = 'ES256'

time_now = datetime.datetime.now()
time_expired = datetime.datetime.now() + datetime.timedelta(hours=12)

headers = {
    "alg": alg,
    "kid": keyId
}

payload = {
    "iss": teamId,
    "exp": int(time_expired.timestamp()),
    "iat": int(time_now.timestamp())
}


if __name__ == "__main__":
    """Create an auth token"""
    token = jwt.encode(payload, secret, algorithm=alg, headers=headers)

    print("----TOKEN----")
    print(token)

However the tokens generated from both scripts return an HTTP 401, What am I doing wrong? Are there any other scripts I could try? Are there any extra requirements I missed? (Besides Team-ID,Key-ID,and AuthKey.p8) I've been at this for a while so any help is appreciated! :D


Solution

  • I ran into the same problem, make sure your AuthKey.p8 file has the key on one line. Yours looks like this:

    -----BEGIN PRIVATE KEY-----
    asdfg1rty5GSM49AgEGCCqGSM49AwEHBHkwdwIBAQQguWRXMHYkuFImkMGByqEPT
    jaXQyO0WK1BjYpuDxIgNQ5nHRRFCuUOi8mgCgYIKoZIzj0DAQehcp0+Z+jwRANCAA
    RCBFg8fL08QS36Fb8HmY+eFrDWMO00w5unCo5n8VyLhvttIZeByXlVsJrK/L3f/
    F2wYmZme
    -----END PRIVATE KEY-----
    

    When it should look like this:

    -----BEGIN PRIVATE KEY-----
    asdfg1rty5GSM49AgEGCCqGSM49AwEHBHkwdwI...
    -----END PRIVATE KEY-----