Rex CoolCode Charles Rex CoolCode Charles - 1 year ago 298
Javascript Question

Basic Authentication Using JavaScript

I am building an application that consumes the Caspio API. 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 NOT have links posted here referencing other material as i have looked at these extensively. Thanks!):

Some references i have looked at:

1) Pure JavaScript code for HTTP Basic Authentication?

2) How to make http authentication in REST API call from javascript

I would like to use this authentication method as described by caspio below:

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:

Method: POST

URL: Your token endpoint

Body: grant_type=client_credentials

Header parameter:

Authorization: Basic Basic authentication realm

Below are my Javascript and HTML 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 -> btoa
var hash = btoa(token);

return "Basic " + hash;

function CallWebAPI() {

// New XMLHTTPRequest
var request = new XMLHttpRequest();"POST", "", false);
request.setRequestHeader("Authorization", authenticateUser(userName, passWord));
// view request status
response.innerHTML = request.responseText;


<div id="response">

<input type="button" class="btn btn-primary" value="Call Web API" onclick="javascript:CallWebAPI();" />

Answer Source

After Spending quite a bit of time looking into this, i came up with the solution for this; In this solution i am not using the Basic authentication but instead went with the oAuth authentication protocol. But to use Basic authentication you should be able to specify this in the "setHeaderRequest" with minimal changes to the rest of the code example. I hope this will be able to help someone else in the future:

var token_ // variable will store the token
var userName = "clientID"; // app clientID
var passWord = "secretKey"; // app clientSecret
var caspioTokenUrl = ""; // Your application token endpoint  
var request = new XMLHttpRequest(); 

function getToken(url, clientID, clientSecret) {
    var key;      "POST", url, true); 
    request.setRequestHeader("Content-type", "application/json");
    request.send("grant_type=client_credentials&client_id="+clientID+"&"+"client_secret="+clientSecret); // specify the credentials to receive the token on request
    request.onreadystatechange = function () {
        if (request.readyState == request.DONE) {
            var response = request.responseText;
            var obj = JSON.parse(response); 
            key = obj.access_token; //store the value of the accesstoken
            token_ = key; // store token in your global variable "token_" or you could simply return the value of the access token from the function
// Get the token
getToken(caspioTokenUrl, userName, passWord);

If you are using the Caspio REST API on some request it may be imperative that you to encode the paramaters for certain request to your endpoint; see the Caspio documentation on this issue;

NOTE: encodedParams is NOT used in this example but was used in my solution.

Now that you have the token stored from the token endpoint you should be able to successfully authenticate for subsequent request from the caspio resource endpoint for your application

function CallWebAPI() {
    var request_ = new XMLHttpRequest();        
    var encodedParams = encodeURIComponent(params);"GET", "", true);
    request_.setRequestHeader("Authorization", "Bearer "+ token_);
    request_.onreadystatechange = function () {
        if (request_.readyState == 4 && request_.readyState == 200) {
            var response = request_.responseText;
            var obj = JSON.parse(response); 
            // handle data as needed... 


This solution does only considers how to successfully make the authenticated request using the Caspio API in pure javascript. There are still many flaws i am sure...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download