Basic authentication using JavaScript

I am creating an application that uses the Caspio API . I am having trouble authenticating their API. I spent 2-3 days trying to figure it out, but it may be due to some understanding on my end. I read countless articles about postoverflow post and otherwise, but didn't solve the problem. Below is a sample code of my solution based on what I was looking at and I get a message with a status code of 400; What am I doing wrong here? (Please provide a sample code with comments, and I would prefer NOT to have the links posted here, citing other materials, as I carefully reviewed them. Thank you!):

Some links that I looked at:

1) Pure JavaScript code for basic HTTP authentication?

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

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

As an alternative to including credentials in the request body, the client can use the basic HTTP authentication scheme. In this case, the authentication request will be configured as follows:

Method: POST

URL: Token Endpoint

Body: grant_type = client_credentials

Header Parameter:

Authorization: Basic authentication conditions

Below are my Javascript and HTML code.

JavaScript:

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(); 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; } 

HTML:

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

+12
source share
3 answers

Having spent a lot of time studying this issue, I found a solution for this; In this solution, I do not use basic authentication, but instead used the oAuth authentication protocol. But in order to use basic authentication, you must be able to specify this in "setHeaderRequest" with minimal changes to the rest of the sample code. I hope this helps someone else in the future:

 var token_ // variable will store the token var userName = "clientID"; // app clientID var passWord = "secretKey"; // app clientSecret var caspioTokenUrl = "https://xxx123.caspio.com/oauth/token"; // Your application token endpoint var request = new XMLHttpRequest(); function getToken(url, clientID, clientSecret) { var key; request.open("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 use the Caspio REST API for any request, you may need to encode the parameters for a specific request to your endpoint; see Caspio documentation on this subject;

NOTE: encoded Params is not used in this example, but was used in my solution.

Now that you have the token stored from the token endpoint, you can successfully authenticate for the subsequent request from the endpoint of the caspio resource for your application

 function CallWebAPI() { var request_ = new XMLHttpRequest(); var encodedParams = encodeURIComponent(params); request_.open("GET", "https://xxx123.caspio.com/rest/v1/tables/", true); request_.setRequestHeader("Authorization", "Bearer "+ token_); request_.send(); 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 only considers how to successfully complete an authenticated request using the Caspio API in pure javascript. I am sure there are still many shortcomings ...

+7
source

Today we use Bearer token more often than Basic Authentication , but if you want Basic Authentication first receive a bearer token, there are several ways:

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

Full syntax here

Second approach using Ajax:

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

Hope this gives you a hint where to start by invoking the API with JS. In frameworks such as Angular 2+, React, etc., there is a more efficient way to call the API using Basic Authentication or Oauth Authentication . Just explore it.

+2
source

The EncodedParams variable is overridden because the params variable does not work. You should have the same predefined variable call, otherwise it looks possible with a bit more work. Hooray! json is not used for its full capabilities in php, there are better ways to call json, which I don't remember at the moment.

-4
source

Source: https://habr.com/ru/post/1240865/


All Articles