Authentication

To use the REST API, you first need to authenticate. In the example on the right side, this happens in real time and based on the modern web standard JWT (JSON Web Token). When a valid combination of username and password is sent, the API generates and returns a JSON Web Token (also called Bearer Token), which is valid for a specified period. For all following API-Calls the token is submitted to and verified by the server.

The usage of Bearer Tokens / JSON Web Tokens is especially interesting in a constellation of multiple APIs / Microservices, since the token can the verified by each server independently thanks to the use of a shared secret key. This leads to a staggering relief of the authentication server, which performance wise often proves as a bottleneck if the credentials have to be verified on each request.



API-Call

After the successful authentication we now can execute a real API-Call. Clicking on the button "Execute API-Call" on the right side, the above code is executed and the answer of the API is pasted in the textfield below.

The bearer token is directly copied from the field "Bearer Token" above, hence there will be an error, when the contained token has been modified. If you already changed the token, you can generate a new one by clicking on the "Authenticate" button again.

If the token is in correct format and valid, the API returns the desired data.

// init request
var request = new XMLHttpRequest();
var data = new FormData();

//fetch the user credentials from the input
var user = document.querySelector('#sg-rest-demo-user').value;
var pass = document.querySelector('#sg-rest-demo-pass').value;

// set user credentials to data
data.append('user', user);
data.append('pass', pass);

// do something after the request executed
request.onreadystatechange = function() {

   // on success
   if (request.readyState === 4 && request.status === 200) {

      var result = JSON.parse(request.responseText);

      var resultString = JSON.stringify(result, null, 4);
      document.getElementById('sg-rest-demo-token-result').value = resultString;

      var bearerToken = result['bearerToken'];
      document.getElementById('sg-rest-demo-token').value = bearerToken;
   }

   // on error
   if (request.readyState === 4 && request.status === 500) {
      var resultString = '{\n error: "Authentication failed." \n }';
      document.getElementById('sg-rest-demo-token-result').value = resultString;
   }
}

// send request
request.open("POST", '/?type=1595576052&tx_sgrest[request]=authentication/authentication/getBearerToken&logintype=login', true);
request.send(data);