Skip to content
This repository was archived by the owner on Jul 4, 2020. It is now read-only.
This repository was archived by the owner on Jul 4, 2020. It is now read-only.

Client Credential auth flow: 400 Bad Request (local browser JS) #639

Description

@jsejcksn

Issue found on 8 August 2017.

Endpoint(s):

  • Auth flow: POST https://accounts.spotify.com/api/token/

Scope(s):

  • None (application is not using authentication)

Steps to reproduce:

See code at this gist

Expected behaviour:

A token is returned.

Actual behaviour:

400 Server Error (consistently)


At this point, I'm simply trying to get a token using the Client Credentials flow. The code is running in a page locally on my computer (so that my client keys aren't exposed to the world). I have included below the content of the linked gist for convenience. Although I can use the curl method successfully, this method fails. One person attempted to help me troubleshoot in issue #321, but without success, so I'm hoping for a repo member to offer a suggestion.

Please advise. Thanks.


Included in an html file using <script src="js/spotify-test.js"></script>:

(() => {

  const myClientInfo = { // but using actual client ID and secret values
    clientID: '<client_id>',
    clientSecret: '<client_secret>'
  };

  const myAuthUrl = new URL('https://accounts.spotify.com/api/token');

  const myAuthHeaders = {
    'Content-Type': 'application/x-www-form-urlencoded',
    Authorization: `Basic ${btoa(`${myClientInfo.clientID}:${myClientInfo.clientSecret}`)}` // Won't work for unicode characters, but I think the Client ID is always ASCII
  };

  const myAuthQueryParams = {
    grant_type: 'client_credentials'
  };

  let myAuthFormBody = new FormData();
  appendObjToFormBody(myAuthQueryParams, myAuthFormBody);

  const myAuthInit = {
    method: 'POST',
    headers: myAuthHeaders,
    body: myAuthFormBody,
    mode: 'no-cors'
  };

  const myAuthRequest = new Request(myAuthUrl, myAuthInit);

  fetch(myAuthRequest)
  .then(res => {
    if (res.ok) {
      return res.json();
    }
    throw new Error('Network response was not ok.');
  })
  .then(data => console.log(data))
  .catch(err => console.log(`Fetch problem: ${err}`));

  function appendObjToFormBody (obj, form) {
    for (let prop in obj) {
      if (obj.hasOwnProperty(prop)) {
        form.append(prop, obj[prop]);
      }
    }
  }

})();

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions