5

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

In that case, would it be acceptable to encrypt the login token on the server side before it's sent to the user, so that they store the encrypted version? Then when the token is sent to the server it gets decrypted and checked to make sure it's valid etc. It's no problem about revoking all user sessions, they're stored in a table and every client request is checked against them. If I clear the table, everyone gets logged out :)
Yes, definitely encrypt it server-side and re-check it upon each API request that the server receives. That's the model that's safest to use as a basic security gate. There's still a few problems with this approach and I'd recommend also setting an CSRF token (in addition to your authToken value). AngularJS supports this secondary token natively and this will adds another barrier to your application. Look through the docs on XSRF here: docs.angularjs.org/api/ng/service/$http

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.