Alomoni
Alomoni

Reputation: 123

How to handle the User Authentication session cookies in angularJS app?

New to AngularJS web development. Currently, I have an application where I have to use the global authentication form. The SPA has multiple partial pages/views. To navigate from tab to tab, I am using ngCookies to store the customer login information.

If the user refreshes the page, I read the cookies and bring the related information for a given customer.

It is working fine but the problem arises when the user closes the application without clicking the logout button and the cookies remain in the browser.

So, the next time another customer logs onto the site, it reads the old cookies and bring the old customer information instead of currently logged-on user.

function writeLoginCustIDCookie(loginCustID) {
$cookies.put("LoginCustID", loginCustID, { path: '/' });
}

function getLoginCustIDCookie() {
return $cookies.get("LoginCustID");
}

Please help me out how to solve this issue.

Upvotes: 0

Views: 1371

Answers (1)

yBrodsky
yBrodsky

Reputation: 5041

You will have to configure a flow. What I do is this:

  • Let the browser handle the cookies. When your server replies with cookies, the browser will set them.
  • Since the browser handled the cookie, all you need to do is add withCredentials: true to your http requests, so that cookies are sent.
  • Now, the user information; when you login, you probably get some response from the server containing the user information. I generally save that to localStorage. That information is NOT sensitive data. Just some basic info.
  • When the user clicks logout, you remove the localStorage data and you dispatch a /logout request to the server.
  • If the user doesn't logout, closes the browser and he comes again....well he will be logged in. That's what happens with most sites. He will be logged in until the cookie expires.
  • If the user comes back after a week, lets say your cookie expired. You will make some request to the backend, the backend will reply 401. Here you catch this error, delete the localStorage data and redirect him to the login page.

This is what I generally do. Nothing crazy I think.

Upvotes: 1

Related Questions