Client Credentials Flow works with curl but not in

2019-09-11 08:36发布

问题:

I am developing a Spotify application and I want to get the token.

I am following Client Credentials Flow and using curl everything works fine:

$ curl -H "Authorization: Basic YjU4Y...llYTQ=" \
-d grant_type=client_credentials \
https://accounts.spotify.com/api/token
# Response:
# {
#   "access_token":"BQD3u...W4iJA",
#   "token_type":"Bearer",
#   "expires_in":3600
# }

And here, there is the Javascript code of my HTML file where I try to get the same result:

var url = "https://accounts.spotify.com/api/token";
var authentication = "YjU4Y...llYTQ=";
var params = { grant_type: "client_credentials" };
var auth = "Basic " + authentication;

$.ajax({
  url: url,
  type: 'POST',
  dataType: 'json',
  headers: {
      'Authorization' : auth,
      'Access-Control-Allow-Origin': '*'
  },
  data: params,
  success: function(data) {
      console.log('success', data);
  }
});

However, I get the following error:

XMLHttpRequest cannot load https://accounts.spotify.com/api/token. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

What am I doing wrong?

Is there really a way to use the Spotify API from a static HTML file using Javascript?

回答1:

Nothing. Browsers disallow CORS unless the server specifically authorizes it. In your case, you don't control the server so you have only one choice - hack the browser. Easily done with plugins for Firefox and Chrome. Search for CORS Everywhere for Firefox. There one for chrome too called access control allow *, or something like that.

Trust me... I spent a week trying a different REST api. Tried js fetch, etc. You must hack the browser with the plugin.