Client Credentials Flow works with curl but not in browser

半腔热情 提交于 2019-12-25 09:30:12

问题


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.



来源:https://stackoverflow.com/questions/41431439/client-credentials-flow-works-with-curl-but-not-in-browser

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