Announcements

Help Wizard

Step 1

NEXT STEP

FAQs

Please see below the most popular frequently asked questions.

Loading article...

Loading faqs...

VIEW ALL

Ongoing Issues

Please see below the current ongoing issues which are under investigation.

Loading issue...

Loading ongoing issues...

VIEW ALL

401 - Unauthorized in some requests

Solved!

401 - Unauthorized in some requests

Plan

Free/Premium

Country

Germany

Operating System

Windows 10

 

My Question or Issue

Hello everyone,

I have a small issue again 🙂 When I make API requests to perform certain actions (such as adding songs to the queue, pausing/resuming playback, setting volume, or skipping songs).

(I'm using the Authorization Code flow.)


The way I generate the Code:
[URL] https://accounts.spotify.com/de/authorize?response_type=token&client_id=..&scope=user-read-currently...


The way I generate/refresh Tokens:

const requestBody = new URLSearchParams();
requestBody.append('grant_type', 'authorization_code');
requestBody.append('code', Code);
requestBody.append('redirect_uri', 'http://localhost');
requestBody.append('client_id', SpoClientID);
requestBody.append('client_secret', SpoClientSecret);

try {
const response = await axios.post(TOKENendpoint, requestBody, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});


Refreshing Tokens:

axios.post(TOKENendpoint, null, {
params: {
grant_type: 'refresh_token',
refresh_token: `${SpotifyRefreshToken}`
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: `Basic ${authString}`
},
})


I'm grateful for any help. Have a wonderful day and stay healthy 🙂

Reply

Accepted Solutions
Marked as solution

I recommend you to generate a new access token, and not a refreshed one.

XimzendSpotify Star
Help others find this answer and click "Accept as Solution".
If you appreciate my answer, maybe give me a Like.
Note: I'm not a Spotify employee.

View solution in original post

12 Replies

You need to add the user-modify-playback-state scope to control playback, as you can read on the respective documentation pages under Authorization scopes:

https://developer.spotify.com/documentation/web-api/reference/add-to-queue

https://developer.spotify.com/documentation/web-api/reference/start-a-users-playback

https://developer.spotify.com/documentation/web-api/reference/set-volume-for-users-playback

https://developer.spotify.com/documentation/web-api/reference/skip-users-playback-to-next-track

P.S. you need to have a Premium subscription to use most or all of the Player scopes.

XimzendSpotify Star
Help others find this answer and click "Accept as Solution".
If you appreciate my answer, maybe give me a Like.
Note: I'm not a Spotify employee.

HUH I was sure I already answered.. sorry!
Yeah I know that and I did it, thats why Im so confused about getting error 401.

Thats the answer I get to the token request, there you can also see the scopes. (And I got Spotify Premium 🙂 )
{
access_token: 'BQAsNIZg1...6SYTiE',
token_type: 'Bearer',
expires_in: 3600,
scope: 'user-modify-playback-state user-read-playback-state user-read-currently-playing'
}

Okay. Error 401 means the token is expired. Have you tried getting a new one?

(I didn't see that scope in your posted URL, but never mind than.)

XimzendSpotify Star
Help others find this answer and click "Accept as Solution".
If you appreciate my answer, maybe give me a Like.
Note: I'm not a Spotify employee.

Yeah, I automatically generate new tokens if the code starts or if the old one expires.

And the error says its invaild and not expired,

status: 401,
statusText: 'Unauthorized',
headers: Object [AxiosHeaders] {
'www-authenticate': 'Bearer realm="spotify", error="invalid_token", error_description="Invalid access token"',


Oh and yeah sorry, I shared the wrong link to you 🙈

Edit: Here the link I actually use: https://accounts.spotify.com/de/authorize?response_type=code&client_id=..&scope=user-read-currently-...

Then I don't know why it doesn't work for you.

XimzendSpotify Star
Help others find this answer and click "Accept as Solution".
If you appreciate my answer, maybe give me a Like.
Note: I'm not a Spotify employee.

Thats sad haha Idk, if I test it in the dev docs (as Example set volume) it works..

But the Code looks fine, right?

async function ManageVolume(channel, message, tags, token) {
    const args = message.split(' ');

    console.log('Volume:', args[1])
    const ManageVolumeEndpoint = `https://api.spotify.com/v1/me/player/volume?volume_percent=${args[1]}`;

    try {
        await axios.put(ManageVolumeEndpoint, {
            headers: {
                Authorization: `Bearer ${token}`
            }
        });
        client.say(channel, `@${tags.username} die Lautstärke wurde erfolgreich auf ${args[1]} gesetzt!`);
    } catch (error) {
        client.say(channel, `@${tags.username} die Lautstärke konnte nicht geändert werden!`);
        console.error('Fehler beim Ändern der Lautstärke:', error);
    }
}
Marked as solution

I recommend you to generate a new access token, and not a refreshed one.

XimzendSpotify Star
Help others find this answer and click "Accept as Solution".
If you appreciate my answer, maybe give me a Like.
Note: I'm not a Spotify employee.

I ll try it later and let you know if it worked. Have a nice day and thank you for the help 🙂

Got still the same problem... And still no Idea what Im doing wrong.. But if I try it at Dev Docs it still works...

{
access_token: 'BQCqpZMghX0mxPEDdC1smFDqfv...TDFQQW9s3nkpBE3qRrcQjqOUjcHv8qOn4QQUKUahEA-yINtVT5rYergy3P0T47GDDgNiP6NzwENUq6ZzxTSjlUxWgspXWEAMoJXWGI_V9GP0y4F8xvcD0nPpG0znlIoZuQ9M4ogCVe',
token_type: 'Bearer',
expires_in: 3600,
refresh_token: 'AQBhAjMzKyfEH3jWCXtXJu...L-_QJvUOURjyQmdMTrW-8UJ_VPmtJUouoRWLB41R8BFiIQN_IHh5bFD0U',
scope: 'user-modify-playback-state user-read-currently-playing'
}

The POST request:

async function addSong(channel, message, tags, FoundSongName, FoundSongUri, artists_names) {
    const uri = FoundSongUri.replace("/",":")
    const AddSongendpoint = ` https://api.spotify.com/v1/me/player/queue?uri=${uri}`

    try {
        await axios.post(AddSongendpoint, {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        })
        client.say(`@${tags.username} der Song ${FoundSongName} - ${artists_names} wurde erfolgreich zur Warteschlange hinzugefügt!`)
   
        const SongQueuefilePath = path.join(__dirname, 'SongQueue.txt');
        const data = `${tags.username} - ${FoundSongName} - ${artists_names} - 0`

        fs.appendFile(SongQueuefilePath, data + '\n', (err) => {
            if (err) {
              console.error('Fehler beim Schreiben in die Datei:', err);
              return;
            }
            console.log('Daten wurden erfolgreich in die Datei geschrieben.');
          });
   
    }
    catch (error) {
        console.log('Error beim hinzufügen des Songs:', error)
        client.say(channel, `@${tags.username} der Song ${FoundSongName} - ${artists_names} konnte nicht in die Warteschlange hinzugefügt werden!`)
   
    }

Response:
response: {
status: 401,
statusText: 'Unauthorized',
headers: Object [AxiosHeaders] {
'www-authenticate': 'Bearer realm="spotify"',
'access-control-allow-origin': '*',
'access-control-allow-headers': 'Accept, App-Platform, Authorization, Content-Type, Origin, Retry-After, Spotify-App-Version, X-Cloud-Trace-Context, client-token, content-access-token',
'access-control-allow-methods': 'GET, POST, OPTIONS, PUT, DELETE, PATCH',
'access-control-allow-credentials': 'true',
'access-control-max-age': '604800',
'content-type': 'application/json',
'strict-transport-security': 'max-age=31536000',
'x-content-type-options': 'nosniff',
date: 'Mon, 25 Dec 2023 18:33:15 GMT',
server: 'envoy',
via: 'HTTP/2 edgeproxy, 1.1 google',
'alt-svc': 'h3=":443"; ma=2592000,h3-29=":443"; ma=2592000',
'transfer-encoding': 'chunked'
}

method: 'post',
url: ' ',
data: '{"headers":{"Authorization":"Bearer BQCqp...-yINtVT5rYergy3P0T47GDDgNiP6NzwENUq6ZzxTSjlUxWgspXWEAMoJXWGI_V9GP0y4F8xvcD0nPpG0znlIoZuQ9M4ogCVe"}}'
},



Add Song to queue works.png

Yoo, just fixed it for add Song, I gave the Headers in the Data object 🙈 Volume still don't works, idk why, but I ll find it out. So thank you again for the help and have nice days!

*edit: Everything works now, tysm 🙂

Hi!
This has to do with the 'scopes', when you create the token you must set the rules for that token, as the documentation mentions here.
https://developer.spotify.com/documentation/web-api/tutorials/code-flow

 

Por example:

var scopes = "user-read-private user-read-email ugc-image-upload user-read-playback-state user-modify-playback-state user-read-currently-playing playlist-read-private playlist-read-collaborative user-read-recently-played";

var client_ID = '2524'
const dev =
  `https://accounts.spotify.com/authorize?client_id=`+client_ID+`&response_type=code&redirect_uri=http://localhost:3000/login&scope=` +
  scopes;

Suggested posts

Type a product name