Angular session timeout and management

Osy picture Osy · May 22, 2013 · Viewed 89.1k times · Source

Is there any way to manage user session using Angularjs?, I mean::

  • Session timeout - when system is idle.
  • Alerts when session is near to expire with option to resume session.
  • Redirect (or any other action) when trying to make a request if session has expired.

Could be Interceptors one good option to solve this problem? Can you provide an example?

Answer

fracz picture fracz · Mar 19, 2015

Try ng-idle. It's simple component where you can set the timeout and warning time before the timeout is reached. Then you can query server for user logout or something similar.

myApp.config(function(IdleProvider, KeepaliveProvider) {
  IdleProvider.idle(900); // 15 min
  IdleProvider.timeout(60);
  KeepaliveProvider.interval(600); // heartbeat every 10 min
  KeepaliveProvider.http('/api/heartbeat'); // URL that makes sure session is alive
});

myApp.run(function($rootScope, Idle) {
  Idle.watch();
  $rootScope.$on('IdleStart', function() { /* Display modal warning or sth */ });
  $rootScope.$on('IdleTimeout', function() { /* Logout user */ });
});

In the above configuration, when user is idle for 900s (does not move mouse, press any key or button etc), warning is being displayed. It will then wait 60s and log out user (send request to a server that possibly destroys server session).

In order to make sure server session does not expire (even if everything user is doing is moving mouse) the Keepalive service will send a request to the server every 10 minutes. This time has to less than server session expiration time.

Checkout the demo.