Angular: set cookie with http request - angularjs

Is there a way to set a cookie with an initial http request?
Meaning, I would like to call a url and set cookies at the same time. Not sure how to go about this? Thank-you
Update: I am not doing cross domain, but sub domain in new tab.

Cookies fly with the HTTP request at the moment those requests depart. So cookies must be already set prior the HTTP request, so the browser can package them.
If you just want to set a cookie prior your request, you can do so by using the $cookies service:
angular.module('cookiesExample', ['ngCookies'])
.controller('ExampleController', ['$cookies', function($cookies) {
// Setting a cookie
$cookies.put('myFavorite', 'oatmeal');
// Make your HTTP Request here //
// $http.get('/someUrl').then(...);
}]);
Now, if you want those cookies being set transparently without the need to scatter $cookies everywhere, you should write a HTTP Interceptor and set those cookies there. You can read how to do it here: https://docs.angularjs.org/api/ng/service/$http (Look for Interceptors).
Once you create your interceptor, which is essentially a Factory, you can hook it up in your .Config stage, like this: $httpProvider.interceptors.push('myHttpInterceptor');. Then, even calls made by the AngularJS Framework will receive this cookie.
If this is not what you want, comment here and I will try to update it.

Related

When is angularjs cookieStore updated with new cookie?

I am currently implementing login functionality in my app. I use AngularJS and $cookieStore. I get a cookie from the server when I make an ajax request to authenticate the user. I want to use this cookie in success() to set up the user in my Auth services. I use chrome developer tools to pause right after I ask for the cookie like this:
var cookieUser = $cookieStore.get('user');
but it turns out to be undefined, but a chrome watch on unescape(document.cookie) shows a cookie "user" is set.
If I run the request twice: $cookieStore.get('user') returns the previous cookie.
Why is $cookieStore not updated with the cookie I just received?
AngularJS' uses an asynchronous $watch callback to write cookies. So you either need to wrap your cookie reading inside a $timeout, or access the data without $cookieStore.get.
I had a similar problem.
After the login was successful in my appplication I had ,of course, to transition to a state 'main.index' and in its resolve object I wasn't able to get the authentication cookie with $cookies object(angular), but I was able to see it in document.cookie.
I think $cookies are refreshed a tiny bit latter than the $.cookie that #swenedo mentioned.
Using $.cookie from jquery worked for me.

AngularJS - Does $resource requests send cookies automatically?

I am using a $resource in my angularJS app. Does it send automatically my cookies? I am doing requests on the same domain.
Browser will always send a cookie along with the request (no matter if it's an XHR request or not) as long as all assumptions are met (same domain, matching path, matching port, same protocol, not expired, etc.).
Since $resource service is just a simple Ajax wrapper your cookies will/should be sent (if everything's in place).
No. But if you want to send cookies, then you can try $cookies service to get the cookie and send with API either in the payload or included in the header.
You can also set the cookie in a default header (with $cookies service injected) so you don't have to specify it in all API calls.
var cookie = $cookies.myCookie; // suppose you already set $cookies.myCookie= 'xxx';
$http.defaults.headers.post.Cookies = cookie;
Note that running different applications on the same domain but on different ports might also be a reason for why cookies are not sent.
Cookies should not be port specific (regarding SOP), but CORS definitely is. Also see Are HTTP cookies port specific?
In my experience no current Browser (FF 47, Chrome 51, IE11) sends cookies for example from localhost:3000 to localhost:8080 in a XHR request.

How to set $httpProvider default headers from my app config in AngularJS?

I'm trying to set my
$httpProvider.defaults.headers.common['X-CSRF-Token'] = $cookie.auth_token;
in my .config section of my app, but it doesn't seem like I can access the document/cookies just yet? Is there a better place to set this?
I'm doing this because I'm storing my users auth_token in a cookie so they don't need to login every time they use my mobile app.
Thanks!
As described in $http docs:
... Angular provides a mechanism to counter XSRF. When performing XHR
requests, the $http service reads a token from a cookie called
XSRF-TOKEN and sets it as the HTTP header X-XSRF-TOKEN.
... To take advantage of this, your server needs to set a token in a
JavaScript readable session cookie called XSRF-TOKEN on the first HTTP
GET request
So if you set your CSRF token in cookie name XSRF-TOKEN then no adjustments are needed on Angular side. and your code should work as is.

Setting cookie from WebApi via angularjs

I'm making a call to the WebApi service, which sets the cookie in the response object.
The call is made from angularjs via $resource
So this is the server code:
CookieHeaderValue cookie = new CookieHeaderValue("Token", "blah") { HttpOnly = true, Expires = DateTime.Now.AddYears(10), Path="/" };
response.Headers.AddCookies(new CookieHeaderValue[] { cookie });
This works, I can see the Set-Cookie header in a response, however the cookie is not being set.
A friend of mine had to set xhrFields' withCredentials to true when he was using jQuery, so I wonder if there's something that needs to be configured in angular as well ?
There could be a number of things going on.
First, since you are on separate domains, you may need to implement CORs (cross origin resource sharing), but it seems that the request is being made successfully. I'm not sure why that works, I would think that browsers would prevent it. In any case here's a jsfiddle that illustrates using CORs with angularjs to make both $http & $resource requests. The trick seems to be to configure the $http service:
$http.defaults.useXDomain = true;
Another thought is that cookies from one domain, can't be accessed by another domain. Here is another question on cookies with angularjs, but the request and server seem to be on the same domain. Here is a discussion on cookie domains, and how they are applied.
If it's possible I would try to get the cookie request/response working on the same domain, and then move the client to another domain.

AngularJS $http and cookies

I'm trying to implement authentication with ExpressJS' cookie sessions and AngularJS. The problem is that even I can get ExpressJS to send session cookies, Angular won't send them with subsequent requests.
I'm running backend server at 192.168.1.2:3000 and yeoman server at 192.168.1.2:3501 so is there a cross-domain issue here? I already did the normal CORS stuff with ExpressJS in order to get $http working correctly but I'm not sure how to get the cookies working.
Have you checked that your request is sent with the withCredentialsflag set to true?
In angular, this can be done by in the HTTP request configuration object, e.g
//...
$http.get(myUrl, {withCredentials: true})
//...
Or if you don't want to reconfigure it all the time, using $httpProvider:
myApp.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.withCredentials = true;
}]);
to get cookies working in angularJS you could follow this link
I maintain session variable in the backend (expressJS) and return it to the $cookies object in the frontend(angularJS).
So When i logout, it would delete the cookie in angularJS and the session variable in the backend.

Resources