How to save session data in an AngularJS application?

I have this web application written in AngularJs that uses cookies to authenticate requests in a REST API.

As soon as the user logs in, the cookie will be received and saved in the browser, and all subsequent requests will send the cookie along with the server. There is a service / object "User" that stores the values ​​of isLoggedIn and the username (for display / stream of the user interface). Now, if I refresh the "index" page, the application restarts. This means that my User object will be cleared. I can check for the presence of a cookie, and if it exists, I can set User.isLoggeIn as true and go from there, but I still need to get the username, ID, etc. So my question is: should I create some kind of ping endpoint in the API to check if the cookie is valid? And if so, the API will send me the user ID and username ... OR should I save the user data in LocalStorage (or some similar cross-browser thing) and just assume the user is logged in if the cookie exists? Any other subsequent requests to pages requiring authentication will be automatically checked. So this question really only applies to the scenario in which the user refreshes the index page - hence restarting the web application. I want to know user data because I want to show "user homepage" instead of "public page".

What do you think?

+7
angularjs cookies session
source share
1 answer

To do this, you should depend on the server. Creating something like GetCurrentUser on the server. If the user is logged in, he returns all the properties of the user.

You should even use this api server to receive user data after authentication is complete. Thus, authentication becomes a two-step process, firstly, user authentication, upon successful completion of another call, the server receives the current user data.

Using local storage on the client side for this would not be ideal, because you had to do a lot of accounting in terms of cleaning up a registered user when you log out or expire a session.

Also, cookies from the server will have an expiration time, and making a decision based on cookies existing on local storage may not be optimal.

+10
source share

All Articles