Authentication with a JavaScript Client

From RAD Studio
Jump to: navigation, search

Go Up to DataSnap REST

If you are writing a client that uses the generated JavaScript proxy to invoke server methods on a server with a TDSAuthenticationManager component configured, you may need to (depending on whether the Implementation of OnUserAuthenticate and OnUserAuthorize consider the values for user and password) pass in your user credentials to the constructor of the JavaScript proxy. To do this, you first need to include a reference in your web page to the base64.js file, which would be included in your project if you used the REST Application wizard. This file can also be found in the dsrest subdirectory of the RAD Studio install location.

<script type="text/javascript" src="js/base64.js"></script>

Once you have that, then just go to where you are already creating an instance of the proxy class and change it to have this new constructor input:

var Proxy = new TServerMethods1(getAuth(USERNAME,PASSWORD));

The getAuth function is a convenience method that uses the base64.js file to encode the user name and password with the required format. USERNAME and PASSWORD should be replaced by their actual values, which can be populated any way you choose, such as creating a form and then pulling their values from that:

<title>Authentication/Authorization Example</title>
<script type="text/javascript" src="base64.js"></script> 
<script type="text/javascript" src="json-min.js"></script> 
<script type="text/javascript" src="ServerFunctionExecutor.js"></script>
<script type="text/javascript" src="ServerFunctions.js"></script>
<script type="text/javascript">
  function doEcho()
    var userName = document.getElementById("namefield"); //get the user name from the form
    var password = document.getElementById("passwordfield"); //get the password from the form

    //create the proxy instance with the specified user credentials
    var Proxy = new TServerMethods1(getAuth(userName, password));
    var Response = Proxy.EchoString("Hello World");
     //Will show an error message if authorization failed,
    //or the JSON Object of parameters if successful
  <form onsubmit="doEcho(); return false;">
    <input id="namefield" type="text"/><br />
    <input id="passwordfield" type="text"/><br />
    <input id="runButton" type="submit" value="INVOKE" />

One thing to note is that all proxy class instances created, and in fact any direct or indirect use of the ServerFunctionExecutor.js code, will use the same Session Id. This means that, once a single server method is invoked, until that session expires, the same Session Id will be used for all future calls from that AJAX client. Since Authentication is only done once, and the user name and password passed in are ignored once successfully authenticated, any change you make to the user name and password will be ignored until you start a new session.

See Also