Authentication (1/3) How to authenticate against the Content Server in REST/Javascript

This is the first post on a series about authentication against the content server. The first post explains the authentication from a html page with Javascript and JQuery using REST

The REST API can be used to perfom things on the Content Server from nearly every thinkable language. Here is the example how to do a login from Javascript.

Replace [yourserver] with the DNS name of your Content Server, replace [yourCSInstance] with your CS instance and the cgi.

A valid URL would be for example

http://AllmyServer.mydomain.com/cs16/cs.exe/api/v1/auth

for the Authentication request.

<script>
  var otcsticket = "";
  /*
  * This function needs to be run first to authenticate the user against Content Server.
  */
  function authenticate() {
  // Set up the ajax request
  $.ajax({
  // Authenticate is a POST
  type: "POST",
  url: "http://[yourserver]/[yourCSInstance]/api/v1/auth",
  data: { username: [username], password: [password] },
  beforeSend: function( xhr ) {
  // Set the correct MimeType for the request.
  xhr.overrideMimeType( "application/x-www-form-urlencoded" )
  }
  }).done( function( data ) {

var val = JSON.parse( data );
  alert( "setting otcsticket to: " + val[ "ticket" ] );
  // Store the ticket for later use.
  otcsticket = val[ "ticket" ];

});
  }
 </script>

To authenticate, a $.ajax call is used. The REST call to do this is “/api/v1/auth”. The data must contain a valid username and a valid password for this user.

If the call is finished, then the JSON array (in the response) must be parsed for the key “ticket”. The value is the authentication token which should be stored somewhere for further use. Normally, the name otcsticket is used for this.

The token should be send as a header in any request, like in this example:

$.ajax( {
  type: "POST",
  url: "[yourURL]/api/v1/nodes",
  data: bodyData,
  headers: { otcsticket: otcsticket },
  beforeSend: function( xhr ) {
  // Set the correct MimeType for the request.
  xhr.overrideMimeType( "application/x-www-form-urlencoded" )
  }
  } ).then( function ( response ) {
  alert("Success")
  }, function ( jqxhr ) {
  alert("failure")
  } );

(This is a call to upload a file, for the complete example on uploading files with REST see the posts in January 2017)