AngularJS withCredentials

I've been working on an AngularJS project which has to send AJAX calls to an restfull webservice. This webservice is on another domain so I had to enable cors on the server. I did this by setting these headers:

cresp.getHttpHeaders().putSingle("Access-Control-Allow-Origin", "http://localhost:8000");
cresp.getHttpHeaders().putSingle("Access-Control-Allow-Credentials", "true");
cresp.getHttpHeaders().putSingle("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
cresp.getHttpHeaders().putSingle("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");

I'm able to send AJAX requests from AngularJS to the backend but I'm facing a problem when I try to get an attribute of a session. I believe this is because the sessionid cookie doesn't get send to the backend.

I was able to fix this in jQuery by setting withCredentials to true.

$("#login").click(function() {
    $.ajax({
        url: "http://localhost:8080/api/login",
        data : '{"identifier" : "admin", "password" : "admin"}',
        contentType : 'application/json',
        type : 'POST',
        xhrFields: {
            withCredentials: true
        },
        success: function(data) {
            console.log(data);
        },
        error: function(data) {
            console.log(data);
        }
    })
});

$("#check").click(function() {
    $.ajax({
        url: "http://localhost:8080/api/ping",
        method: "GET",
        xhrFields: {
            withCredentials: true
        },
        success: function(data) {
            console.log(data);
        }
    })
});

The problem that I'm facing is that I can't get this to work in AngularJS with the $http service. I tried it like this:

$http.post("http://localhost:8080/api/login", $scope.credentials, {withCredentials : true}).
            success(function(data) {
                $location.path('/');
                console.log(data);
            }).
            error(function(data, error) {
                console.log(error);
            });

Can anyone tell me what I'm doing wrong?


You should pass a configuration object, like so

$http.post(url, {withCredentials: true, ...})

or in older versions:

$http({withCredentials: true, ...}).post(...)

See also your other question.


In your app config function add this :

$httpProvider.defaults.withCredentials = true;

It will append this header for all your requests.

Dont forget to inject $httpProvider

EDIT : 2015-07-29

Here is another solution :

HttpIntercepter can be used for adding common headers as well as common parameters.

Add this in your config :

$httpProvider.interceptors.push('UtimfHttpIntercepter');

and create factory with name UtimfHttpIntercepter

    angular.module('utimf.services', [])
    .factory('UtimfHttpIntercepter', UtimfHttpIntercepter)

    UtimfHttpIntercepter.$inject = ['$q'];
    function UtimfHttpIntercepter($q) {
    var authFactory = {};

    var _request = function (config) {
        config.headers = config.headers || {}; // change/add hearders
        config.data = config.data || {}; // change/add post data
        config.params = config.params || {}; //change/add querystring params            

        return config || $q.when(config);
    }

    var _requestError = function (rejection) {
        // handle if there is a request error
        return $q.reject(rejection);
    }

    var _response = function(response){
        // handle your response
        return response || $q.when(response);
    }

    var _responseError = function (rejection) {
        // handle if there is a request error
        return $q.reject(rejection);
    }

    authFactory.request = _request;
    authFactory.requestError = _requestError;
    authFactory.response = _response;
    authFactory.responseError = _responseError;
    return authFactory;
}