I'm building an AngularJS application that interacts with an API that uses authentication tokens to authenticate users. Everything seems to be working fine, but I'm struggling with a way to properly persist the authentication token between requests.
At the moment, when a user logs in with correct credentials an authToken
is returned, and I'm setting that on $rootScope.authToken
. I'm also sending that auth token for future requests, but if I do a hard reload reload the webpage with F5 $rootScope
gets cleared and I have to authenticate again.
I'm aware I can store the authToken in a cookie, but would that be the most secure way? Am I better off using local storage to store the token? If local storage is used, would that not get cleared when the user restarts their browser? I'd ideally like the login to persist for a few days.
Firstly, I'm not sure what the format of your authToken
is but localStorage
should not be used for any sensitive data. Using localStorage
works great (and survives browser restarts) as long as your authToken
is relatively tamper-proof either through some form of encryption or nonce.
Essentially, you should be careful that since the value is "visible" to all client-side users it should be assumed to be possible to modify or increment.
Have you thought about revocation of login sessions? For example, if you want to log out all active sessions of your application, how would you do it? Since the authToken
is stored client-side, you may need to add a timestamp (or some other unique value) to it that can be checked server-side.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With