AngularJS: Can not read session value

All we need is an easy explanation of the problem, so here it is.

  • The session is set by server when the user logs in

I want to retrieve this value in my angular front end, but it says undefined

The relevant code is

   $scope.logout = function () {
        console.log('session value', $cookieStore.get('session'));
    }

and my app is also configured to include ngCookies

var app = angular.module('myApp', ['ngCookies']);

when I run my application, i see

session value undefined 

I can however, see the session in Chrome Dev Tools

AngularJS: Can not read session value

What is that I am missing?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

What is that I am missing?

The server set the cookie as Session cookie (HttpOnly flag). This means that you cannot access this cookie on the client. The client will send the cookie to the server on each request but the client has no access to its value. That’s the very definition of an HttpOnly cookie. If you want to be able to access this cookie value on the client you should modify your server side script so that when it is setting the cookie it doesn’t append the HttpOnly flag to it. Obviously this comes with the corresponding disclaimer about the security vulnerability that you might be opening on your site depending on the purpose and specific value stored in this cookie.

Method 2

UPDATE

It is worth noting that $cookieStore is deprecated and now for accessing the cookies one should use ngCookies (see ngCookies).

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply