Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out if user is still logged in using session based authentication?

I know this has been asked countless times, but none of the answers I found described the actual connection to backend.

I have a one-page JS app that communicates with small backend (Django) API. I use session based authentication. User info is cached on first load. If session expires, I need to change page header and flush user info from cache. However, most of my API resources are public and return always 200. Several other resources are private and return 403 if user isn't logged in, which is great as this gives me excatly the information I need. The problem is, some pages access public resources only. In case session is suddenly deleted on backend and user navigates to url that accesses only public resources, user info isn't flushed and I have an UX problem.

My initial idea was to request private user resource (let's call it /users/self/) on every url change which returns 200 in case user is authenticated and 403 in case they aren't. This however requires 1 extra request before every other request for each url change, which isn't really ideal.

Are there any easier techniques I could use in this case? I don't mind even switching to other type of authentication if that would solve the problem.

like image 633
Ondrej Slinták Avatar asked Apr 25 '14 12:04

Ondrej Slinták


1 Answers

What i have done and seen for such scenarios is to use some type of http interceptor that intercept all http requests done by Angular and if it finds a response status of 401, such interceptors raise an event using $rootScope.

See one library here https://github.com/witoldsz/angular-http-auth

To use it, one needs to subscribe to the events raise using some type of root controller, which can redirect the user to login page.

See an example here https://medium.com/opinionated-angularjs/7bbf0346acec

like image 165
Chandermani Avatar answered Oct 12 '22 00:10

Chandermani