Search code examples
javascriptangularjsrestcurlngresource

Angularjs Rest endpoint with username password


I am trying to write a Single Page App (SPA) based on AngularJS. The app should connect to a webserver that provides a RestFul services, but each end point requires username and password along with other parameters. Since I am a beginner in this area, before moving towards the actual development, I tried PostMan/Advanced Rest Client chrome extensions to verify the basic connections. A sample request preview :

POST /servicesNS/admin/search/search/jobs/export HTTP/1.1
Host: localhost:8089
Cache-Control: no-cache
Content-Type: application/x-www-form-urlencoded

search=search+error+|+table+host&output_data=xml&username=admin&password=unity3d

This is actually equivalent to the cURL command:

curl  -k -u admin:unity3d --data-urlencode search="search error | table host" -d "output_mode=xml" https://localhost:8089/servicesNS/admin/search/search/jobs/result

After getting successful results in above mentioned ways, I am now looking for equivalent way of doing it in AngularJS.

var app = angular.module('TabsApp', []);
app.controller('TabsCtrl', function ($scope, $http)
{
    login = function () {

        $scope.userName ="admin";
        $scope.password ="unity3d"

        $http({
            method :"POST",
            url:"https://localhost:8089/servicesNS/admin/search/search/jobs/export",
            data: { "username" :  "admin" , "password": "unity3d", "search" : "search error"},
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}

        }).success(function (data, status, headers, config) {
            console.log('status',status);
            console.log('data',status);
            console.log('headers',status);
        });
    }
});

This gives me error 401 Unauthorized, the headers of the response:

> Remote Address:127.0.0.1:8089 Request
> URL:https://localhost:8089/servicesNS/admin/search/search/jobs/export
> Request Method:POST Status Code:401 Unauthorized Request Headersview
> source Accept:application/json, text/plain, */* Accept-Encoding:gzip,
> deflate Accept-Language:en-US,en;q=0.8 Connection:keep-alive
> Content-Length:65 Content-Type:application/x-www-form-urlencoded
> Host:localhost:8089 Origin:http://localhost:63342
> Referer:http://localhost:63342/UI/UI1.html User-Agent:Mozilla/5.0
> (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)
> Chrome/39.0.2171.71 Safari/537.36 Form Dataview sourceview URL encoded
> {"username":"admin","password":"unity3d","search":"search error"}:
> Response Headersview source Access-Control-Allow-Credentials:true
> Access-Control-Allow-Headers:Authorization
> Access-Control-Allow-Methods:GET,POST,PUT,DELETE,HEAD,OPTIONS
> Access-Control-Allow-Origin:* Cache-Control:private
> Connection:Keep-Alive Content-Length:130 Content-Type:text/xml;
> charset=UTF-8 Date:Sat, 29 Nov 2014 19:53:59 GMT Server:Splunkd
> Vary:Cookie, Authorization WWW-Authenticate:Basic realm="/splunk"
> X-Content-Type-Options:nosniff X-Frame-Options:SAMEORIGIN

And the output is :

<?xml version="1.0" encoding="UTF-8"?> <response>   <messages>
    <msg type="ERROR">Unauthorized</msg>   </messages> </response>

Any idea what is going wrong?


Solution

  • If you are sending response in the format of 'application/x-www-form-urlencoded' the actual data format should be the same.

    What you are sending currently is a JSON object. You would need to use $http tranformer to tranform the request: Something in line of

                transformRequest: function (data) {
                    var postData = [];
                    for (var prop in data)
                    postData.push(encodeURIComponent(prop) + "=" + encodeURIComponent(data[prop]));
                    return postData.join("&");
                },
    

    See a working fiddle here http://jsfiddle.net/cmyworld/doLhmgL6/