Timsen
Timsen

Reputation: 4126

Make cookie presistent even after browser shutdown/restart using Angular.js

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;

}

Upvotes: 1

Views: 2769

Answers (2)

Adrian Lopez
Adrian Lopez

Reputation: 2877

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.

Upvotes: 1

Khanh TO
Khanh TO

Reputation: 48972

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.

Upvotes: 3

Related Questions