Spotify API error 400: “only valid bearer authentication supported”

拈花ヽ惹草 提交于 2021-02-11 13:37:30

问题


I was using the api to try and get the data of my profile through the access token. I used the given code from the authorization example code given in the website, and I used

        let parsed = queryString.parse(window.location.search);
        let accessToken = parsed.access_token;
        console.log(parsed);
        console.log(accessToken);
        fetch('https://api.spotify.com/v1/me', {
            headers: {'Authorization': 'Bearer' + accessToken},
            json: true
        }).then((res) => res.json())
        .then(data => console.log(data));
    }

But the 400 error still appears even though the access token works. I even checked in the try it method for that specific function and with the same token, it was able to get the data. For relevant info of what I changed in the example code for authentication, I changed redirect_uri = "localhost:8888/callback" and then I also changed

res.redirect('http://localhost:3000/profile/?' +
          querystring.stringify({
            access_token: access_token,
            refresh_token: refresh_token
          }));
      }

to go to my profile page for my app. I was wondering if I somehow needed to give permission to my profile page but I already added it to redirect urls just in case. Thanks for reading


回答1:


There must be a space between "Bearer" and your token. That is what's missing.

let parsed = queryString.parse(window.location.search);
    let accessToken = parsed.access_token;
    console.log(parsed);
    console.log(accessToken);
    fetch('https://api.spotify.com/v1/me', {
        headers: {'Authorization': 'Bearer ' + accessToken},
        json: true
    }).then((res) => res.json())
    .then(data => console.log(data));
}

Notice how I added a space after "Bearer".

It is also present on spotify's site in their sample code. https://developer.spotify.com/documentation/general/guides/authorization-guide/ (there was no permalink, just search for "bearer" on this page)

Also, I would suggest you use template literals to define such strings, as it's easier, more readable and may prevent such errors in the future.

headers: {'Authorization': `Bearer ${accessToken}`}

You can read more about this here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals



来源:https://stackoverflow.com/questions/60425737/spotify-api-error-400-only-valid-bearer-authentication-supported

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!