Tech Blog‎ > ‎Geek corner‎ > ‎

Basic Authentication using Custom Endpoint

posted Sep 12, 2016, 9:13 AM by Unknown user   [ updated Sep 19, 2016, 1:59 PM by Laura Carrubba ]

As an API developer, you can use a custom endpoint for greater flexibility. One request was to support basic authentication (passing username and password). You can extract and decode the authentication string and use these values to create a Live API Creator authentication token. You can use this token to make REST API calls to Live API Creator and return JSON responses.

For more information about how a create custom endpoint, see Custom Endpoints.

  1. Create a new custom endpoint - check GET and POST.
  2. Enter the following code, changing the authURL to your project:
    var res = {};
    var hdrs = headers.getRequestHeader('Authorization');

    for (var i = 0; i < hdrs.size(); ++i) {
      var auth = hdrs.get(i);
      var decode = Java.type("com.kahuna.server.util.Base64Util.decode");
      var userpw = new decode(auth.substring(6));

      var split = userpw.split(":");
      var username = split[0];
      var password = split[1];
      var data = { 'username': username, 'password': password};
      var authURL = "http://localhost:8080/rest/default/demo/v1";
      var apikey = SysUtility.restPost(authURL +"/@authentication",null,null,data);
      var authtoken = JSON.parse(apikey).apikey;
      var settings = {headers: { "Authorization": "CALiveAPICreator "+authtoken+":1"}};
      var params = {};
      var url = authURL + "/demo:customer";
      res = SysUtility.restGet(url,params,settings);

    //FOR POST verb

      var reader = new;
      var json = "";
      var line = "";
      while ((line = reader.readLine()) != null) {
        json += line;
      } res = SysUtility.restPost(url,params, settings, json);
      } //if auth
     } //for loop
    } //if hdrs - or throw exception
    return JSON.stringify(res);
  3. Go to your favorite tool, such as cURL or Postman, and create a basic authentication (username: demo, password: Password1).
  4. If you do a verb GET, use restGET. If you use POST, use restPOST and pass the 'json' content.