jQuery: Use REST to Authenticate Against Apprenda

Follow

REST authentication on Apprenda is quite straightforward. Developers can make a REST call from any client to the JSON authentication URL for their target Apprenda instance.

In Apprenda Platform version 5.0.0 and later

The call should be a POST request with the username, password, and tenant (as of version 5.0.0, a user may belong to more than one tenant, so it is necessary to specify under which tenant the user will authenticate) JSON formatted in the body of the request. Upon successful login, the platform will return an object representing the newly established session. One parameter on that object is the apprendaSessionToken parameter. This token value must be passed with any future requests during this session. It can be passed in POST requests as JSON in the body of the request, or as an HTTP header called ApprendaSessionToken.

Here is an example of how to authenticate via REST, using JSON, using jQuery's built in ajax() function.

var user = "myemail@myemail.com";
var pw = "mypassword";
var tenant = "mytenant" var authToken = null; $.ajax({
url: 'http://apps.[yourapprendaurl]/api/services/json/r/authentication(v1)/CitadelService/IJSONAuthenticationService/Login/',
type: "POST",
contentType: 'application/json',
data: JSON.stringify({ "Username" : user, "Password" : pw, "Tenant" : tenant}),
success: function(data)
{
authToken = data.apprendaSessionToken;
}
});

In Apprenda Platform versions prior to 5.0.0:

The call should be a POST request with the username, password, and login type (use "SaaSGrid") JSON formatted in the body of the request. Upon successful login, the platform will return an object representing the newly established session. One parameter on that object is the Token parameter. This token value must be passed with any future requests during this session. It can be passed in POST requests as JSON in the body of the request, or as an HTTP header called authenticationToken.

Here is an example of how to authenticate via REST, using JSON, using jQuery's built in ajax() function.

var user = "myemail@myemail.com";
var pw = "mypassword";
var authToken = null;
$.ajax({
url: 'http://apps.[yourapprendaurl]/api/services/json/r/authentication(v1)/CitadelService/IJSONAuthenticationService/Login/',
type: "POST",
contentType: 'application/json',
data: JSON.stringify({ "Username" : user, "Password" : pw, "Type" : "SaaSGrid"}),
success: function(data)
{
authToken = data.Token;
}
});
Have more questions? Submit a request

Comments

  • Avatar
    Jonathan Hallée

    Matt,

    Does the service support cross domain requests? When we are trying to authentication from another domain we always get a Bad gateway error with no more details.

    Thanks,

    Jonathan

  • Avatar
    Matt

    Jonathan,

    It certainly should.  I'm not aware of anything preventing it from working.  Bad Gateway error, though, sounds more to me like you might have a bad URL you're requesting - can you share your code?

    Matt

  • Avatar
    Yann Larente

    Hi Matt,

    I'm Jonathan's coworker, here's how we try to do it, from our remote client application. (This code works when calling it from our Apprenda GUI app but not from our client app) 

    It looks pretty much the same as the one posted here but here it is! 

    <code>

    var user = "myUserName@email.com";

    var pw = "myPwd";

    var authToken = null;

    $.ajax({

    url: 'http://apps.myDomain.com/api/services/json/r/authentication(v1)/CitadelService/IJSONAuthenticationService/Login',

    type: "POST",

    contentType: 'application/json',

    data: JSON.stringify({ "Username": user, "Password": pw, "Type": "SaaSGrid" }),

    success: function (data) {

    authToken = data.Token;

    alert("Success!");

    },

    error: function (jqXHR, textStatus, errorThrown) {

    alert("jqXHR : " + jqXHR +

    " \n**** text Status : " + textStatus +

    " \n**** text Status : " + errorThrown);

    }

    });

    </code

     

     

  • Avatar
    Matt

    Hi Yann,

    Can you capture the full error response from the server (via Fiddler or your browser developer tools)?  Thanks.

    Matt

  • Avatar
    Jonathan Hallée

    Matt,

     

    After some changes we have made it farther but still not working yet. Here is the code, as you can see we try with https :

     

    $.ajax({

    url: "https://apps.isaixcloud.com/api/services/json/r/authentication(v1)/CitadelService/IJSONAuthenticationService/Login",

    type: "POST",

    crossDomain: true,

    contentType: 'application/json',

    data: JSON.stringify({ "Username": user, "Password": pw, "Type": "SaaSGrid" }),

    success: function (data) {

    authToken = data.Token;

    alert("Success! data is : " + authToken);

    },

    error: function (jqXHR, textStatus, errorThrown) {

    alert("jqXHR : " + jqXHR +

    " \n**** text Status : " + textStatus +

    " \n**** text Status : " + errorThrown);

    }

    });

    And using fiddler we see the following (in 2 parts), first it tries to connect and we get the following. As we can see the connection is successfull

    CONNECT apps.isaixcloud.com:443 HTTP/1.1

    Host: apps.isaixcloud.com

    Connection: keep-alive

    User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.56 Safari/536.5

    HTTP/1.1 200 Connection Established

    FiddlerGateway: Direct

    StartTime: 12:42:25.713

    Connection: close

    And after that it requests the authentication service and we get the following (We get the bad gateway error): 

    OPTIONS /api/services/json/r/authentication(v1)/CitadelService/IJSONAuthenticationService/Login HTTP/1.1

    Host: apps.isaixcloud.com

    Connection: keep-alive

    Access-Control-Request-Method: POST

    Origin: null

    User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.56 Safari/536.5

    Access-Control-Request-Headers: origin, content-type, accept

    Accept: */*

    Accept-Encoding: gzip,deflate,sdch

    Accept-Language: en-US,en;q=0.8,fr-CA;q=0.6,fr;q=0.4

    Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

    HTTP/1.1 502 Bad Gateway

    Content-Type: text/html

    Server: Microsoft-IIS/7.5

    X-Powered-By: ASP.NET

    Date: Thu, 14 Jun 2012 16:42:22 GMT

    Content-Length: 1477

     

     

     

    Weird, connection is successfull we it throws a bad gateway AFTER the connection was established...

  • Avatar
    Jonathan Hallée

    Note that I tried from my local IIS server, it fixed the origin null, because throws the same errors

  • Avatar
    Jonathan Hallée

    Matt, Here is the latest info on our attempt to authenticate using REST : We are now trying on a machine in the same network as our Apprenda environment to get rid of the 502 error but now we are getting something even stranger. With the same code as mentionned earlier in this thread we receive this :


    HTTP/1.0 501 Not Implemented

    Content-Type: text/html

    Content-Length: 28

    Expires: now

    Pragma: no-cache

    Cache-control: no-cache,no-store

    This method may not be used.


    And here is the request headers :


    OPTIONS https://apps.isaixcloud.com/api/services/json/r/authentication(v1)/CitadelService/IJSONAuthenticationService/Login HTTP/1.1

    Host: apps.isaixcloud.com

    Connection: keep-alive

    Access-Control-Request-Method: POST

    Origin: http://localhost

    User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.56 Safari/536.5

    Access-Control-Request-Headers: origin, content-type, accept

    Accept: */*

    Referer: http://localhost/testREST/

    Accept-Encoding: gzip,deflate,sdch

    Accept-Language: en-US,en;q=0.8

    Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3


    Sounds to me that something is wrong with the service

  • Avatar
    Matt

    Jonathan / Yann,

    We'll have to try to replicate your use case.  We'll do some investigation and get back to you.

    Matt

  • Avatar
    Jonathan Hallée

    Matt,

    Have you investigated our use case yet?

     

    As far as I am concerned, I have been able to get more details on the bad gateway error : It actually is 502.3 saying :

     

    502.3 The connection with the server was terminated abnormally

     

    I am having the same error as described here :  http://forums.iis.net/t/1182687.aspx

    Seems to be related to URL rewrite. I checked the url rewrite rules on the IIS server but can't find errors.

     

    Maybe it can help you.

     

    Thanks,

    Jonathan

  • Avatar
    Jonathan Hallée

    Matt,

     

    I am joining files representig the trace that was done in IIS during the 502.3 error....

     

    There are a couple of strange things... When you open the xml file, go in the compact view at line 34, we see that the url is re-written to : 

    http://SG - Router12000Farm/services/json/r/authentication(v1)/CitadelService/IJSONAuthenticationService/Login

    Any ideas? Apparently with the error code, it is the following : ERROR_WINHTTP_CONNECTION_ERROR     
    All my firewalls are down... 

  • Avatar
    Jonathan Hallée

    Oups, here are the files. The xml and the stylesheet

  • Avatar
    Jonathan Hallée

    I also tested by registering on apprendacloud.com and I have the same behavior. 502 bad gateway. Is it to version 3.5?

  • Avatar
    Matt

    Jonathan,

    That URL rewrite rule is correct.  I'll take a look at Apprenda Cloud to see what's going on.  Based on what you've sent, it should be working.

    Matt

  • Avatar
    Anilraj

    Hi Matt Ammerman,

     Can you share me the sample code.

    Regards,

    Anilraj

  • Avatar
    Anilraj

    Hi,

    I was successfull in getting the authentication token. After getting the athentication token i want to navigate to an application deployed in apprenda. Can u share me the code to navigate to that page using the authentication token.

    Regards,

    Anilraj

  • Avatar
    Matt

    Anilraj,

    You'll want to use JavaScript to navigate in the success handler of your authentication call.

    window.location.href= your URL

    You do not need to use the authentication token to do so. The authentication token is only used when you call your secured web services. If you are intending to navigate to a secured user interface, you don't need to authenticate via REST, you want to have users login using the platform's login screen which will put an authentication cookie in their browser.

    Matt

  • Avatar
    Anilraj

    Hi Matt,

    Thanks for the info. I have deployed a wcf service into apprenda. as i have the authentication token how can i call a service. Can you share me a code sample. I do not want to use any apprenda dlls. i saw a blog post

    http://apprenda.com/blog/general/mobile-development-using-the-apprenda-platform/#comment-557

    But i was not clear on how to move further.

    Regards,

    Anilraj

  • Avatar
    Bernie Herdan

    Hi Anilraj,

    This tutorial was targeted for people trying to authenticate with REST using a mobile application, but it should contain the information you need to call a service running on Apprenda using REST Authentication.

    Please let me know if you have any quesitions,

    Bernie

  • Avatar
    Anilraj

    Hi Bernei,

    Am facing problem with calling a wcf method with paramters. It is giving me bad gateway error. Please look over the code below

    Below is my wcf service method

     [OperationContract]

     [WebGet(UriTemplate = "/AuthorizeCreditCard/{creditCardInformationString}")]

      CreditCardResult AuthorizeCreditCard(string creditCardInformationString);

     

    And in client am calling the method

    string url = "http://apps.apprenda.local/api/services/json/r/restserviceccauth(v1)/AuthenticateService/IAuthenticateService/AuthorizeCreditCard/" + creditCardString + "";

    req = (HttpWebRequest)HttpWebRequest.Create(url);

    req.Method = "GET";

    req.Headers.Add("AuthenticationToken", authToken.Value);

    req.Headers.Add("Accepts", "application/json");

    req.ContentType = "application/json";

    req.Host = "apps.apprenda.local";

    req.ContentLength = 0;

    var response = (HttpWebResponse)req.GetResponse();

    var dataContractSerializer = new DataContractSerializer(typeof(string));

    using (var responseStream = response.GetResponseStream())

    {

      //string a = (string)dataContractSerializer.ReadObject(responseStream);

      creditCardResult = (CreditCardResult)dataContractSerializer.ReadObject(responseStream);

    }

    response.Close();

    Regards,

    Anilraj

  • Avatar
    Bernie Herdan

    Hi Anilraj,

    A bad gateway error usually means that an exception was thrown behind our load balancer. In this case, that means that the exception is coming from your service.

    You should debug your process to see where your application is failing.

    Regards,

    Bernie

  • Avatar
    Yash Kedia

    Hi Bernie,

    I am trying to integrate my application with Apprenda. I want to authenticate users from my system and directly redirect them to the applications in Apprenda, bypassing the login page of Apprenda. I am tried using the REST API call to make from the client of my application but i am getting the error message as

    XMLHttpRequest cannot load https://apps.test.atosdemo.net/api/services/json/r/authentication(v1)/CitadelService/IJSONAuthenticationService/Login/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://atosnacloudpov.service-now.com' is therefore not allowed access. The response had HTTP status code 502.

    Below is the code used at client:

    var user = "***";
    var pw = "
    *";
    var authToken = null;
    $j.ajax({
    url: 'https://apps.test.
    ***.net/api/services/json/r/authentication(v1)/CitadelService/IJSONAuthenticationService/Login/',
    type: "POST",
    contentType: 'application/json',
    data: JSON.stringify({ "Username" : user, "Password" : pw, "Type" : "SaaSGrid"}),
    success: function(data)
    {
    authToken = data.Token;
    alert(authToken);
    }
    });

    Any suggestion or help is appreciated.

    Thanks.