Basic Authentication Using JavaScript

pure javascript basic authentication
node.js https request basic authentication
http basic authentication header username:password example
node js basic authentication request
nodejs basic auth
express-basic-auth github
axios basic auth
basic auth java

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();" />

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_.status == 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...

NodeJS, A client that wants to authenticate itself with a server can then do so by including an Authorization request header field with the credentials. In the Connections pane, expand the server name, expand Sites, and then click the site, application or Web service for which you want to enable basic authentication. Scroll to the Security section in the Home pane, and then double-click Authentication. In the Authentication pane, select Basic Authentication, and then, in the Actions pane, click Enable.

Today we use Bearer token more often that Basic Authentication but if you want to have Basic Authentication first to get Bearer token then there is a couple ways:

const request = new XMLHttpRequest();'GET', url, false, username,password)
request.onreadystatechange = function() {
        // D some business logics here if you receive return
   if(request.readyState === 4 && request.status === 200) {

Full syntax is here

Second Approach using Ajax:

  type: "GET",
  url: "",
  dataType: 'json',
  async: false,
  username: "username",
  password: "password",
  data: '{ "key":"sample" }',
  success: function (){
    alert('Thanks for your up vote!');

Hopefully, this provides you a hint where to start API calls with JS. In Frameworks like Angular, React, etc there are more powerful ways to make API call with Basic Authentication or Oauth Authentication. Just explore it.

Basic authentication - MDN, js request object to the module export. If parsing fails undefined is returned, otherwise an object with .name and .pass . var  The syntax for basic authentication is { Authorization: Basic c3V2b2pxxxxxxx==} Instead of Bearer try with Basic.

EncodedParams variable is redefined as params variable will not work. You need to have same predefined call to variable, otherwise it looks possible with a little more work. Cheers! json is not used to its full capabilities in php there are better ways to call json which I don't recall at the moment.

basic-auth, Hi All,. I have an requirement to set Basic authentication in the HTTP header. This is required within a javascript because I need to call edge  But it is a valid suggestion as far as knowledge and content.The opp explicitly asked JSON web service that require basic authentication using jQuery (OR ANYTING THAT WOULD WORK, REALLY) Therefore as a shot in the dark the suggestion is fine.

Set basic authentication in header in javascript, Learn how to use HTTP Basic Authentication with jQuery Ajax or raw javascript XmlHttpRequest interface. Basic authentication should only be used with HTTPS, otherwise the password can be exposed to everyone. If the client request protected resource without providing credentials, the server will reject the request and send back 401 HTTP status and WWW-Authenticate header.

HTTP Basic Authentication with jQuery AJAX requests, js, check out our beginner guide here. We are going to start with the most basic one, the HTTP Basic authentication,  If you have a backend server asking for the Basic Auth credentials before the app then this is sufficient, it will re-use that then: fetch(url, { credentials: 'include', }).then(); share | improve this answer | follow | | | |

Web Authentication Methods Explained, Use Basic authentication in Node.js and use HTTP headers in the request to pass user credentials. The "Basic" HTTP authentication scheme is defined in RFC 7617, which transmits credentials as user ID/password pairs, encoded using base64. Security of basic authentication As the user ID and password are passed over the network as clear text (it is base64 encoded, but base64 is a reversible encoding), the basic authentication scheme is not secure.