How to store logged in user's info?

All we need is an easy explanation of the problem, so here it is.

I have angular app, user can login using email/password, and server will return token.

Now I have angular service to keep user’s data, but if page reload, user logged out.

Should I store that token, in order to make further API calls?

How and where I should store that token?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

My recommendation is to store the token in local storage, if you are using HTML5. It’s as simple as:

localStorage['clientToken'] = clientToken;

To pass the token back to the server, you can use a HTTP header and a Angular httpInterceptor:

$httpProvider.interceptors.push(function($q, $log, $location) {
  return {
    'request': function(config) {
      config.headers['clientToken'] = localStorage['clientToken'];
      return config;
    }
  });

Some example can be found here.

Method 2

For non HTML5 scenarios, you can use simply cookies. Angular provides nice support of it with help of $cookieStore.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply