$cookieStore.get() return undefined in angularjs - angularjs

I'm writing a cookie from a server through the response and it's fine the problem is when I try to read the same cookie using angularJs $cookieStore.get() returns always 'undefined', I have debugged with the developer tools using chrome and the cookie is there,
console.log($cookieStore.get("r"));
the $cookieStore seems to be injected and running ok, I'm just wondering why angularJs can't read the cookie.
Edit:
I tried with $cookies service and I get undefined as well.
I send the cookie in the server side without any problem, I'm getting the cookie in chrome developer tools
I'm using Service Stack and the code is the following:
public override object Logout(IServiceBase service, ServiceStack.ServiceInterface.Auth.Auth request)
{
var resp = service.RequestContext.Get<IHttpResponse>();
resp.Cookies.AddCookie(new Cookie { Name = "r", Path = "/", Value = "from server", HttpOnly = false, Discard = false, Expires = DateTime.Now.AddHours(12) });
return base.Logout(service, request);
}

I think $cookieStore is only meant to be used by itself, was 'r' set somewhere else? The docs say it provides a key/value store backed by cookies, not direct access to cookies. When I set 'myValue' to 'jason' it stores %22jason%22 (fiddle). This means you can set values to javascript objects if you want and the cookieStore will serialize and deserialize them for you.
Try using $cookies instead where you can just set properties and the values aren't encoded (fiddle):
$scope.setValue = function() {
$cookieStore.put("myValue", $scope.value);
};
$scope.getValue = function() {
$scope.value = $cookieStore.get('myValue');
};
$scope.setCookieValue = function() {
$cookies.otherValue = $scope.value;
};
$scope.getCookieValue = function() {
$scope.value = $cookies.otherValue;
};

Yes #Pedro is right in .NET ,for example, when doing an authentication with HttpCookie by default the attribute HttpOnly is true and in javscript -> document.cookie cant find the cookie you just saved to the browser.
It worked for me by setting to false HttpOnly when saving the cookie.

Related

How is client side authentication implemented in MEAN.JS?

Can someone tell how is authentication actually working in MEAN.JS [meanjs.org] here?
When the user logs in,where is the USER json object stored. The code is
// Authentication service for user variables
angular.module('users').factory('Authentication', [
function() {
var _this = this;
_this._data = {
user: window.user
};
return _this._data;
}
]);
//The implementation of the service in the controller
$scope.authentication=Authentication;
// If successful we assign the response to the global user model
$scope.authentication.user = response;
but in console window.user returns null
Another question, how the app retains the user JSON object when the page is refreshed? After the page is refreshed window.user returns the user JSON object, I don't see this object in the Local Storage or Session Storage, neither do i see any ajax being made to the server to fetch this object.
Thanks

Angular $cookieStore not retaining updated cookie on refresh

I'm having issues with $cookieStore retaining a cookie value after updating it. Here are two methods of a UserService that deals with the cookie:
var getCurrentUser = function () {
return $cookieStore.get('currentUser');
};
var updateCurrentUser = function () {
return $http.get(baseUrl + 'api/session').then(function (response) {
$cookieStore.put('currentUser', response.data);
$rootScope.$broadcast('currentUser', response.data);
}, function (response) {
$cookieStore.remove('currentUser');
$rootScope.$broadcast('currentUser', null);
});
};
Throughout my app, after an action is executed that would affect the current user's meta data, I call UserService.updateCurrentUser() which retrieves the latest user data from the server and updates that cookie. Then, in places that display the user data, I have the following code that will update the user model in that particular controller:
$scope.$on('currentUser', function (event, data) {
$scope.user = data;
});
As I step through the code, everything appears to be working correctly. After the $cookieStore.put('currentUser', response.data); line runs, the updated value can be confirmed by checking $cookieStore.get('currentUser'). When I check the actual cookie using a browser tool, however, the cookie value is not updated. I'm not sure if the browser tool requires a refresh to show the new data. But when I refresh the page, the updated cookie value is also no where to be seen. What is going on?
Thanks in advance.
Check out the documentation adding a cookie using $cookie service:
put(key, value, [options]);
The third argument allows additional options:
path (string)
domain (string)
expires (date)
secure (boolean)
You should set "expires" to define when the cookie should expire, otherwise the cookie will expire when you refresh or leave the site.
$cookies.put("id", 1, {
expires: new Date(2016, 1, 1)
});
Also the service is now called $cookies. Since Angular 1.4 you can now set expiry. Until then it wasn't possible.
http://docs.angularjs.org/api/ngCookies/service/$cookies

Setting and getting objects in cookies with Angular 1.2

I'm trying to set user properties in cookies. On login, the following code is run:
$scope.$parent.session.user = response.data.user;
// Get profile information
$http.get('api/v1/profiles/' + response.data.user.id)
.then(function(response){
$scope.$parent.session.user.profile = response.data;
});
// Set cookie data
console.log($scope.$parent.session.user);
$cookieStore.put('user', $scope.$parent.session.user);
The logged data includes the profile object, so I assume that this is placed into cookies too.
When the app is loaded, I look for cookies with:
if ($cookieStore.get('user')){
$scope.session.user = $cookieStore.get('user');
}
This returns just the user object, without the profile object. What am I doing wrong here?
It's weird that you say it is logged correctly, but it still looks like a synchronity issue. You should set the cookie in the body of the $http callback..
$http.get('api/v1/profiles/' + response.data.user.id)
.then(function(response){
$scope.$parent.session.user.profile = response.data;
$cookieStore.put('user', $scope.$parent.session.user);
});

can't get access to angular.js $cookies object

I am using the angular.js and csrf (Cross-site request forgery).
I have added the angular cookie file.
script src="angular-cookies.js"
And then, to load it in the application:
angular.module('myApp', ['ngCookies']);
It’s really easy to add the CSRF token in the headers of the $http service. We just need to configure it into the run process of the application, requiring the $cookie and $http services.
.run(function ($http, $cookies) {
$http.defaults.headers.post['x-csrf-token'] = $cookies._csrf;
});
in the browser debug console, I can find the cookie is existing.
However,when the page is loaded, $cookies outputs undefined, it is strange the $cookies object itself is undefined, but obviously I have loaded the cookie.js and inject the module into the application
This is on the node.js server side, which how I set a CSRF token on the cookie
app.use(require('csurf')());
app.use(function(req, res, next){
res.locals.token = req.csrfToken();
res.cookie('XSRF_TOKEN', req.csrfToken(),{ maxAge: 900000, httpOnly: false });
next();
});
Thanks for the reminding, I changed the
res.cookie('XSRF_TOKEN', req.csrfToken(),{ maxAge: 900000 });
to
res.cookie('XSRF_TOKEN', req.csrfToken(),{ maxAge: 900000, httpOnly: false });
so the cookie is readable from the browser.
According to angularJS documentation
Your server needs to set a token in a JavaScript readable session cookie called XSRF-TOKEN on the first HTTP GET request.
This cookie must be readable with Javascript, and ideally sent with the index.html page.
When this is done, you should see it in your browser (options / cookies ...)
At this point, you should access it in your angular code.
If this is not the case, may you should try to access it with pure Javascript
_getCookie = function(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++){
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
};
getCookie("XRSF_TOKEN");
Your cookie is probably being set as HttpOnly = true which will set the cookie but will not allow the client to view it therefore it comes back as undefined. You will need to make sure this flag is set to false.

AngularJS $cookies, getting undefined

I'm trying to retrieve Cookies using the $cookies service provided by ngCookies but I keep getting 'undefined', I really don't know what it's wrong...
I can clearly see the cookie displayed in the Dev Console in Chrome.
AND I also set a XSRF-TOKEN cookie and Angular's $http is NOT including it as a Header (X-XSRF-TOKEN) which I think it's the same problem.
Laravel by default encrypts Cookies and are extremely long, could that be it?
If I set a cookie with the $cookies service, it appears and I can retrieve it withou issue, so the $cookies service is working.... :P
angular.module("MachinatorApp.Services.SectionService", [])
.factory("SectionService", ["$http", "$cookies", function($http, $cookies) {
console.log($cookies.laravel_session);
var doRequest = function(action, id) {
var params = $.param({
"action" : action,
"id" : id
});
return $http({
method : 'POST',
url : "/Sections/" + action,
data : params,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
});
}
return {
sections: function(action, id) {
return doRequest(action, id);
}
}
}]);
I found out what the solution was by looking a the Laravel API Documentation, Cooke::make() by default sends a HttpOnly cookie, that's why I could not read it from Angular, Adding false to the httpOnly parameter fixes the issue, Although Now I think it's just safer to leave it http only and read from the header's cookies.
http://laravel.com/api/4.1/
search for Cookie, click CookieJar, make method
Cookie::make("XSRF-TOKEN", Session::token(), 0, null, null, null, false))
This sends a NON HTTP ONLY Cookie which you can read from angularJS

Resources