1

I am using Angular for my project, and got into a problem with authentication. On successfull authentication user retrive a token from server, and as long user have this token he can access all the places where he need authentication (i thought its a best way to do this since i use MVC web API as backend, and i dont have sessions). Everything works fine, until i close down my browser, and start it up again $cookieStore and $cookies are empty after restart.

Does anyone have any idea how to make cookie presistent, or are there any smarter way of doing this?

Ive created a test controller with a testview where i have 2 buttons which set and load $cookie before restart it works, if i open a new window while the other one is still up its works too, but as soon i close everything down, coockies is empty.

    $scope.Set = function () {

    $scope.LoadedData = "test";
    $cookies.myFavorite = 'oatmeal';

}


$scope.Load = function () {

    var b = $cookies.myFavorite;
    console.log("testasdasd" + $cookies);

    $scope.LoadedData = $cookies.myFavorite;

}
Adrian Lopez
  • 2,601
  • 5
  • 31
  • 48
Timsen
  • 4,066
  • 10
  • 59
  • 117

2 Answers2

3

There are 2 types of cookies: session cookie and persistent cookie.

  • Session cookie is in memory and only survives until you close the browser.
  • Persistent cookie will be saved into disc and will be expired based on the Expires property.

The decision to save the cookie as session or persistent is server side, not your client side javascript.

When you use .NET Forms authentication, you can use FormsAuthentication.GetAuthCookie to create a cookie, the second parameter determines if this is a session or a persistent cookie.

Khanh TO
  • 48,509
  • 13
  • 99
  • 115
  • can i use FormsAuthentication even if i dont use forms authentication? – Timsen Jan 10 '14 at 13:56
  • @Timsen: In asp.net framework, Form authentication is actually a module registered in the pipeline to intercept requests before they reach your Handlers. I think it's possible, but you have to implement it yourself. You have to write your own module and register it with the framework and intercept the requests yourself. – Khanh TO Jan 10 '14 at 13:59
  • @Timsen: Why not just enable it by specifying a configuration in web.config? – Khanh TO Jan 10 '14 at 14:01
1

I know this question was already answered, but actually you CAN manage cookies persistence client side. Just $cookieStore.

Persistent cookie:

// from your controller
$cookieStore.put('auth_token', token);
// in your module
$http.defaults.headers.common.Authorization = $cookieStore.get('auth_token');

In the module, we are telling angular that we want to use this session everytime any page of our website it's loaded.

EDIT: You may be interested in HTML5 localstorage instead of cookies.

Community
  • 1
  • 1
Adrian Lopez
  • 2,601
  • 5
  • 31
  • 48