MusicKit - Authorization failed: AUTHORIZATION_ERROR: Unauthorized

Hello,

I am having difficulties with configuring MusicKit correctly for my web app that I am building, seeking assistance with the issues I am having. Would greatly appreciate any help!

After allowing access to the following,

"Access Request media.mydomain.com would like to access Apple Music, media library, and listening activity for myemail'@icloud.com.",

I get a popup error that states, "Authorization failed. Please try again.".

Following is the information that is given in developer console:

[Error] Failed to load resource: the server responded with a status of 403 () (webPlayerLogout, line 0) [Error] Authorization failed: AUTHORIZATION_ERROR: Unauthorized (anonymous function) (media.mydomain.com:398)

Answered by _Pancras in 820115022

Hi,

I created the Node file and i am able to generate the token:

const fs = require('fs');

const privateKeyPath = '/Users/demo/AuthKey_***.p8'; // Path to the .p8 file
const teamId = 'XXXX'; // Your Apple Developer Team ID
const keyId = 'XXXX'; // Key ID for MusicKit

const privateKey = fs.readFileSync(privateKeyPath, 'utf8');

const token = jwt.sign(
  {
    iss: teamId, // Issuer: Your Apple Developer Team ID
    iat: Math.floor(Date.now() / 1000), // Issued at: Current timestamp in seconds
    exp: Math.floor(Date.now() / 1000) + (60 * 60 * 24 * 180), // Expiration: 180 days from now
    aud: 'appstoreconnect-v1' // Audience: Identifies the intended recipient
  },
  privateKey, // Private key used for signing the token
  {
    algorithm: 'ES256', // Signing algorithm (Elliptic Curve)
    header: { kid: keyId } // Key ID included in the header of the token
  }
);

console.log(token)

I just the following HTML code to test the token:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Apple Music Player</title>
    <script src="https://js-cdn.music.apple.com/musickit/v1/musickit.js"></script>
</head>
<body>
    <h1>Apple Music Player</h1>
    <button id="authorize">Authorize</button>
    <button id="play">Play Preview</button>
    <button id="playFull">Play Full Song</button>
    <script>
        // Configure MusicKit
        MusicKit.configure({
            developerToken: 'TOKEN', // Replace with your actual developer token
            app: {
                name: 'My Music App',
                build: '1.0.0'
            }
        });

        // Get an instance of MusicKit
        const music = MusicKit.getInstance();

        // Handle Authorization Button
        document.getElementById('authorize').addEventListener('click', async () => {
            try {
                await music.authorize(); // Prompts the user to authorize
                alert('Authorized! You can now play full songs.');
            } catch (error) {
                console.error('Authorization failed:', error);
            }
        });

        // Handle Play Preview Button
        document.getElementById('play').addEventListener('click', async () => {
            try {
                // Play a preview of a song
                await music.setQueue({ songs: ['203709340'] }); // Replace with a valid Apple Music song ID
                music.play();
            } catch (error) {
                console.error('Error playing preview:', error);
            }
        });

        // Handle Play Full Song Button
        document.getElementById('playFull').addEventListener('click', async () => {
            try {
                if (!music.isAuthorized) {
                    alert('Please authorize first to play full songs!');
                    return;
                }
                // Play a full-length song (requires user authorization)
                await music.setQueue({ songs: ['1559745848'] }); // Replace with a valid Apple Music song ID
                music.play();
            } catch (error) {
                console.error('Error playing full song:', error);
            }
        });
    </script>
</body>
</html>

Hi,

Was also looking into the JS stuff for my app. Did you create the tokens and enable access to MusicKit in your Dev Account?

-P

Hi _Pancras,

What I did was create an Identifier>Media ID as "media.com.mydomain", downloaded my MusicKit Key (created using the Media ID), then used script to generate token. Not really sure what to do from here, next step is to reach out to Apple support 🤷🏻‍♂️

Here is the script I am using to generate token:

// generate_token.js const jwt = require('jsonwebtoken'); const fs = require('fs');

// Adjust these to your Apple Developer details: const privateKeyPath = '/home/theloungeuser/AuthKey_mykey.p8'; // Path to the .p8 const teamId = 'myTeamID'; // Your Apple Developer Team ID const keyId = 'myKeyID'; // 10-char Key ID for MusicKit

// Read the private key const privateKey = fs.readFileSync(privateKeyPath, 'utf8');

// Generate Apple MusicKit dev token (valid max 180 days) const token = jwt.sign( { iss: teamId, iat: Math.floor(Date.now() / 1000), exp: Math.floor(Date.now() / 1000) + (60 * 60 * 24 * 180), // 180 days aud: 'appstoreconnect-v1' }, privateKey, { algorithm: 'ES256', header: { kid: keyId } } );

console.log(token);

Accepted Answer

Hi,

I created the Node file and i am able to generate the token:

const fs = require('fs');

const privateKeyPath = '/Users/demo/AuthKey_***.p8'; // Path to the .p8 file
const teamId = 'XXXX'; // Your Apple Developer Team ID
const keyId = 'XXXX'; // Key ID for MusicKit

const privateKey = fs.readFileSync(privateKeyPath, 'utf8');

const token = jwt.sign(
  {
    iss: teamId, // Issuer: Your Apple Developer Team ID
    iat: Math.floor(Date.now() / 1000), // Issued at: Current timestamp in seconds
    exp: Math.floor(Date.now() / 1000) + (60 * 60 * 24 * 180), // Expiration: 180 days from now
    aud: 'appstoreconnect-v1' // Audience: Identifies the intended recipient
  },
  privateKey, // Private key used for signing the token
  {
    algorithm: 'ES256', // Signing algorithm (Elliptic Curve)
    header: { kid: keyId } // Key ID included in the header of the token
  }
);

console.log(token)

I just the following HTML code to test the token:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Apple Music Player</title>
    <script src="https://js-cdn.music.apple.com/musickit/v1/musickit.js"></script>
</head>
<body>
    <h1>Apple Music Player</h1>
    <button id="authorize">Authorize</button>
    <button id="play">Play Preview</button>
    <button id="playFull">Play Full Song</button>
    <script>
        // Configure MusicKit
        MusicKit.configure({
            developerToken: 'TOKEN', // Replace with your actual developer token
            app: {
                name: 'My Music App',
                build: '1.0.0'
            }
        });

        // Get an instance of MusicKit
        const music = MusicKit.getInstance();

        // Handle Authorization Button
        document.getElementById('authorize').addEventListener('click', async () => {
            try {
                await music.authorize(); // Prompts the user to authorize
                alert('Authorized! You can now play full songs.');
            } catch (error) {
                console.error('Authorization failed:', error);
            }
        });

        // Handle Play Preview Button
        document.getElementById('play').addEventListener('click', async () => {
            try {
                // Play a preview of a song
                await music.setQueue({ songs: ['203709340'] }); // Replace with a valid Apple Music song ID
                music.play();
            } catch (error) {
                console.error('Error playing preview:', error);
            }
        });

        // Handle Play Full Song Button
        document.getElementById('playFull').addEventListener('click', async () => {
            try {
                if (!music.isAuthorized) {
                    alert('Please authorize first to play full songs!');
                    return;
                }
                // Play a full-length song (requires user authorization)
                await music.setQueue({ songs: ['1559745848'] }); // Replace with a valid Apple Music song ID
                music.play();
            } catch (error) {
                console.error('Error playing full song:', error);
            }
        });
    </script>
</body>
</html>

Pancras,

Thank you for responding to my post, I appreciate any feedback. My apologies for the delayed reply, I have been traveling and haven't been able to make any adjustments to my work.

I recall you mentioning that you were attempting to use MusicKit for your application and was wondering if you were experiencing the same/similar issue I was experiencing when posting my original thread, "[Error] Failed to load resource: the server responded with a status of 403 () (webPlayerLogout, line 0) [Error] Authorization failed: AUTHORIZATION_ERROR: Unauthorized (anonymous function) (media.mydomain.com:398)"?

When I try to generate a token using the script you provided, I am experiencing error(s), although I've been able to successfully generate a token with the following script. Each time I test (using v3 in my html code), though, I am getting authentication errors (these errors have been occurring since I've adjusted code to use the v3 music kit version instead of v1 in my html code):

// generate_token.js const jwt = require('jsonwebtoken'); const fs = require('fs');

// Adjust these to your Apple Developer details: const privateKeyPath = '/home/theloungeuser/AuthKey_*****.p8'; // Path to the .p8 const teamId = 'My TeamID'; // Your Apple Developer Team ID const keyId = 'KeyID'; // 10-char Key ID for MusicKit

// Read the private key const privateKey = fs.readFileSync(privateKeyPath, 'utf8');

// Generate Apple MusicKit dev token (valid max 180 days) const token = jwt.sign( { iss: teamId, iat: Math.floor(Date.now() / 1000), exp: Math.floor(Date.now() / 1000) + (60 * 60 * 24 * 180), // 180 days aud: 'appstoreconnect-v1' }, privateKey, { algorithm: 'ES256', header: { kid: keyId } } );

console.log(token);

Here are the errors I am seeing in browser developer console when testing using the html code you've provided:

[Error] Failed to load resource: the server responded with a status of 403 () (webPlayerLogout, line 0) [Error] Authorization failed: AUTHORIZATION_ERROR: Unauthorized MKError — musickit.js:13:6433 (anonymous function) — musickit.js:28:274505 asyncGeneratorStep$w — musickit.js:28:271538 _next — musickit.js:28:271785 (anonymous function) (media.mydomain.com:398)

Figured out that my Nginx configuration for my project included a root path (/var/www/media/html/index.html)for index.html that was different from the location where I was editing index.html from. I somehow managed to created an additional index.html file in my home folder (/home/theloungeuser/index.html) that I was editing from, I switched the root path in Nginx configuration to "/home/theloungeuser".

I'm rebuilding my web player, which I started with the minimal script Pancras provided and have been working to integrate the features I had setup using v1 before attempting to migrate to v3. I am able to successfully authorize when signing into my paid Apple Music Account, although the music.player/music.api.library is not loading how it should, "Radio" not working. I can see images of artists/songs in the "Home" section of my Apple Music player as well as when I search for an artist/song, though they cannot be interacted with. When I click any artist/song, nothing happens.

I am seeing the following information of my Firefox developer console:

A resource is blocked by OpaqueResponseBlocking, please check browser console for details. play--v3.png MusicKit loaded and event triggered. media.mydomain.com:396:15 Attempting to authorize with Apple Music... media.mydomain.com:442:15 Opening multiple popups was blocked due to lack of user activation. musickit.js:13:86737 Storage access automatically granted for origin “https://authorize.music.apple.com%E2%80%9D on “https://media.mydomain.com”. Authorization successful media.mydomain.com:445:17 music.player is not available; skipping player event listeners. media.mydomain.com:455:19 music.api.library is not available. Skipping library calls. media.domain.com:462:19 music.player not available; cannot play item.

MusicKit - Authorization failed: AUTHORIZATION_ERROR: Unauthorized
 
 
Q