Implementing session inactivity timeout in Angular using @ng-idle/keepalive package

Posted by

Implementing Session Inactivity Timeout in Angular

Implementing Session Inactivity Timeout in Angular

Session inactivity timeout is an important feature in web applications to improve security by automatically logging out users after a certain period of inactivity. In Angular, this can be achieved using the @ng-idle/keepalive package.

Setting up @ng-idle/keepalive package

To implement session inactivity timeout in Angular, we can use the @ng-idle/keepalive package. First, we need to install the package using npm:


npm install @ng-idle/keepalive

Once the package is installed, we need to import it into our Angular application and configure the session timeout behavior.

Configuring session timeout behavior

We can configure the session timeout behavior by setting up the idle and timeout periods, as well as the timeout notification and logout actions. Here’s an example configuration:


import { Idle, DEFAULT_INTERRUPTSOURCES } from '@ng-idle/core';
import { Keepalive } from '@ng-idle/keepalive';

export class SessionTimeoutService {

constructor(private idle: Idle, private keepalive: Keepalive) {
idle.setIdle(900); // 15 minutes of inactivity
idle.setTimeout(60); // 1 minute timeout warning
idle.setInterrupts(DEFAULT_INTERRUPTSOURCES);

idle.onTimeout.subscribe(() => {
// Perform logout action
});

idle.onTimeoutWarning.subscribe((countdown) => {
// Display timeout warning to user
});

idle.watch();
}

resetTimer() {
this.idle.watch();
}

}

Using session timeout service in components

Once the session timeout service is set up, we can use it in our Angular components to reset the timeout timer whenever the user interacts with the application. This can be achieved by calling the resetTimer method of the session timeout service whenever a user action occurs.


import { Component } from '@angular/core';
import { SessionTimeoutService } from './session-timeout.service';

@Component({
selector: 'app-root',
template: `

`,
providers: [SessionTimeoutService]
})
export class AppComponent {

constructor(private sessionTimeoutService: SessionTimeoutService) {}

resetSessionTimer() {
this.sessionTimeoutService.resetTimer();
}
}

By implementing session inactivity timeout using the @ng-idle/keepalive package, we can enhance the security and user experience of our Angular applications.

0 0 votes
Article Rating
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@user-og9dq8tr3x
7 months ago

Thanks for the tutorial. What if a System goes to sleep mode or User Locks the computer? Does this code works? I used ng-idle and it dint work for me.

@user-qx3do8ft3k
7 months ago

Good 👍.. keep it up