Search code examples
javascriptajaxapiauthenticationcast-iron

Consuming API Which is having Secure Username and Password i.e Authentication


How to consume IBM Cast iron API in Mobile Application. The API is having authentication like Username & Password (401 Authorization Required). The Problem here is how to authenticate the API in javascript using Ajax call.

This is My code:

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            $("#bSubmit").click(function () {
                alert("Button Clicked");
                var xmlString;
                var username = 'myusername';
                var password = 'mypassword';
                $.ajax({
                    url: 'MYURL',
                    crossDomain: true,
                    headers: {
                        "Authorization": "Basic " + btoa(username + ":" + password)
                    },

                    type: "POST", //This is what you should chage
                    dataType: "xml",
                    contentType: "application/xml; charset=utf-8",
                    }).done(function (response) {
                        alert("Sucess"+response);
                            xmlString = (new XMLSerializer()).serializeToString(response);
                             $("#displayout").html(xmlString);
                    }).fail(function (request, textStatus, errorThrown) {
                        alert("wrong");
                        alert(textStatus + " : " + errorThrown.toString());
                 });
                });
          });
    </script>
</head>
<body>
    <input type="text" name="1" id="txt1">
    <input type="submit" name="b" value="Submit" id="bSubmit"> 
    <div id="displayout">
    </div>
</body>

I have Added CORS filter in firefox and IE. This is working fine in IE. But it is not working in firefox and Chrome.

In IE: I changed the setting by the following this link It is working for me.

In firefox console it is displaying like:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://MYURL. This can be fixed by moving the resource to the same domain or enabling CORS.

In Chrome console it is displaying like:

OPTIONS https://MYURL 401 (Authorization Required)

XMLHttpRequest cannot load https://MYURL. Invalid HTTP status code 401

Could you please help me out.


Solution

  • Using Java I got Response. But using AJAX call still it is the same error like an authorisation problem.

    Java based code:

    public class Sample {
    public static void main(String[] args) throws Exception {
         final String userid = "username";
         final String pwd = "password";
         String addressXML="";
         String url="URL";
        //Create an instance of HttpClient.
        final HttpClient client = new HttpClient();
        //com.sun.jersey.api.client.ClientResponse response;
        final URL uri = new URL(url);
        final GetMethod getmethods = new GetMethod(url);
        AuthScope authscope = new AuthScope(uri.getHost(), uri.getPort());
        Credentials defaultcreds = new UsernamePasswordCredentials(userid, pwd);
        client.getState().setCredentials(authscope, defaultcreds);
        getmethods.setDoAuthentication(true);
        client.getParams().setAuthenticationPreemptive(true);
        final int responseCode = client.executeMethod(getmethods);
        if (responseCode == 200) {
            InputStream in = getmethods.getResponseBodyAsStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuilder out = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                out.append(line);
            }
            addressXML = out.toString();
            System.out.println("Resultent Data" + addressXML);   //Prints the string content read from input stream  nodes 
            reader.close();
        } else {
            throw new RuntimeException("Failed : HTTP error code : " + responseCode + " address rs service error!");
        }
    }}