title: Basic Authentication Using JavaScript
body: <p>I am building an application that consumes the <a href="http://howto.caspio.com/integration/web-services-api/rest-api/authenticating-rest/" rel="noreferrer">Caspio API</a>. I am having some trouble authenticating against their API. I have spent 2-3 days trying to figure this out but it may be due to some understanding on my end. I have read countless articles on stackoverflow post and otherwise but have not solved the issue. Below is a code example of my solution based on what i have looked at and i am getting a 400 Status code message; What am i doing wrong here? (Please provide well commented code example and i would prefer to <strong>NOT</strong> have links posted here referencing other material as i have looked at these extensively. Thanks!):</p>
  
  <p>Some references i have looked at:</p>
  
  <p>1) <a href="https://stackoverflow.com/questions/491914/pure-javascript-code-for-http-basic-authentication">Pure JavaScript code for HTTP Basic Authentication?</a> </p>
  
  <p>2) <a href="https://stackoverflow.com/questions/22413921/how-to-make-http-authentication-in-rest-api-call-from-javascript?rq=1">How to make http authentication in REST API call from javascript</a></p>
  
  <p>I would like to use this authentication method as described by caspio below: </p>
  
  <p>As an alternative to including credentials in the request body, a client can use the HTTP Basic authentication scheme. In this case, authentication request will be setup in the following way:</p>
  
  <p><strong><em>Method:</em></strong> POST</p>
  
  <p><strong><em>URL:</em></strong>    Your token endpoint</p>
  
  <p><strong><em>Body:</em></strong>   grant_type=client_credentials</p>
  
  <p><strong><em>Header parameter:</em></strong></p>
  
  <p><strong><em>Authorization:</em></strong> Basic Basic authentication realm</p>
  
  <p>Below are my Javascript and HTML code.</p>
  
  <p><strong>JavaScript:</strong></p>
  
  <pre><code>var userName = "clientID";
  var passWord = "secretKey";
  
  function authenticateUser(user, password)
  {
      var token = user + ":" + password;
  
      // Should i be encoding this value????? does it matter???
      // Base64 Encoding -&gt; btoa
      var hash = btoa(token); 
  
      return "Basic " + hash;
  }
  
  function CallWebAPI() {
  
      // New XMLHTTPRequest
      var request = new XMLHttpRequest();
      request.open("POST", "https://xxx123.caspio.com/oauth/token", false);
      request.setRequestHeader("Authorization", authenticateUser(userName, passWord));  
      request.send();
      // view request status
      alert(request.status);
      response.innerHTML = request.responseText;
  }
  </code></pre>
  
  <p><strong>HTML:</strong></p>
  
  <pre><code>&lt;div&gt;
  &lt;div id="response"&gt;
  
  &lt;/div&gt;
  &lt;input type="button" class="btn btn-primary" value="Call Web API" onclick="javascript:CallWebAPI();" /&gt;
  </code></pre>
  
  <p></p>