9

I know I can use localstorage or SQLite but I'm not sure how to exactly do that.

In my app, I'm getting the session token in the Login controller where I make post request to the server and in return get session token.

I'm not sure how to make this token globally accessible.

P.S: I'm very new to AngularJs.

Vineonardo
  • 183
  • 1
  • 4
  • 12
  • For local Storage example please refer to this blog [link](https://blog.nraboy.com/2014/06/saving-data-with-ionicframework/) – Anil kumar Aug 19 '15 at 08:07

1 Answers1

23

in your controller once you get the token from the server

$scope.token = token;

you can say

localStorage.setItem("token", $scope.token);

then when you want to fetch the token (say in another controller) all you have to say is

$scope.token = localStorage.getItem("token");

Also if they re-open the app you can even check to see if they already have a token

if(localStorage.getItem("token") !== null && localStorage.getItem("token") !== ""){//go ahead and authenticate them without getting a new token.}

Also be aware that on logout if you want to clear the token you can just set

localStorage.setItem("token", "");

but be aware you can only set local storage to strings, not booleans or null.

UPDATE: I see that people are still referencing this, and wanted to add a caveat. On IOS, the local cache seems to be cleared by the OS automatically. I am not sure what triggers this, but I have ran into issues with and users loosing their settings stored in local storage. If that would be an issue for you, I recommend looking at something like IndexedDB, pouchdb, sqllite, or other alternatives.

Jess Patton
  • 2,476
  • 1
  • 15
  • 26
  • 1
    What if the token expired? – ca9163d9 Mar 01 '17 at 04:49
  • Then check if the token is expired (hit an api endpoint), if so delete it or overwrite it. – Jess Patton Mar 01 '17 at 13:18
  • Super new to AngularJS here too. Is this considered secure on iOS and Android? Disregarding all older versions of these platforms, is this secure today? – Citricguy Apr 03 '18 at 09:40
  • For the most part yes, the local storage is only accessible by the domain it was set on, if someone had physical access to the machine and had dev tools they could read it, but if they had phsyical access to the machine you are open to alot more than just someone pulling local storage. I would not store credit cards info in local storage, but expiring tokens, maybe page settings, would work just fine. – Jess Patton Apr 03 '18 at 14:22