AngularJS withCredentials Not Sending

In AngularJS, I have my Restful API in a subdomain, but I have a problem with the fact that cookie / session is not used in domains. For Angular, I do this:

app.config(['$httpProvider', function($httpProvider) { $httpProvider.defaults.useXDomain = true; $httpProvider.defaults.withCredentials = true; delete $httpProvider.defaults.headers.common['X-Requested-With']; }]); 

Also, when I make a request with $ http, I do

 var object = {}; object.url = '/example' object.withCredentials = true; $http(object).success(object.success).error(object.error); 

And On my server side I have:

 if($_SERVER['REQUEST_METHOD']=='OPTIONS') { if(isset($_SERVER['HTTP_X_FOWARDED_HOST']) && !empty($_SERVER['HTTP_X_FOWARDED_HOST'])) { $origin=$_SERVER['HTTP_X_FOWARDED_HOST']; } else { $origin=$_SERVER['HTTP_ORIGIN']; } if(isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']) && ($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']=='POST' || $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']=='DELETE' || $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']=='PUT')) { header('Access-Control-Allow-Origin: '.$origin); header('Access-Control-Allow-Credentials: true'); header('Access-Control-Allow-Headers: *,X-Requested-With,Content-Type'); //header('Access-Control-Allow-Headers: Content-Type'); header('Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT'); // http://stackoverflow.com/a/7605119/578667 header('Access-Control-Max-Age: 86400'); } } 

Now I see that the server says that it allows credentials, but is not sent in the options request. Screenshot below.

enter image description here What am I doing wrong?

+5
javascript angularjs ajax php cors
source share
1 answer

By default, credentials are NOT sent in an OPORS request before flying. See here . See also answer . Credentials will be sent at your actual request.

Additionally, the use of the XDomain and X-Request-With headers is not actually used in current versions of angular, so these lines do nothing in your $ httpProvider configuration. All interaction with CORS is handled by the browser itself and your server.

In general, for the correct implementation of CORS, your server does not need to request credentials in the preflight check request. (Please note that some browsers send them anyway, but should not.) This is because the OPTIONS request is considered “safe” and should never contain sensitive information.

Perhaps your problem is with cookies that you are trying to use in different domains. What cookies are you trying to send to where?

+11
source share

All Articles