Optimizing Security and User Experience with Angular Session Timeout
2 min readJan 17, 2024
Session timeout after 10 minutes in angular.
Steps:
Initialization:
- Import necessary modules and services from Angular.
- Set up the component with animations and required dependencies.
Session Timeout Logic:
- Use a
Subject
to track user inactivity. - Set an initial session timeout of 10 minutes (600,000 milliseconds) upon component initialization. (feel free to adjust your time)
User Activity Detection:
- Implement a
HostListener
to track mouse movements. - Utilize
debounce
to optimize performance and avoid unnecessary calls.
Resetting Timeout:
- When user activity is detected, clear the existing timeout.
- Set a new session timeout to maintain a 10-minute idle period.
Logout Functionality:
- Implement a
logOut
function for handling user logout. - Close any open dialogs.
- Invoke the sign-out method from the
AuthGuardService
. - Navigate the user to a session timeout page.
Router Navigation:
- Ensure proper navigation after user logout.
- Redirect users to a designated page, such as
/session-timeout
.
Error Handling:
- Consider adding error handling to address potential issues during the sign-out process.
- code for above logic:
import {
Component,
HostListener,
OnInit,
} from '@angular/core';
import { Router } from '@angular/router';
import { Subject } from 'rxjs';
import { AuthGuardService } from './services/auth-guard.service';
import { debounce } from 'lodash';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
animations: [onMainContentChange],
})
export class AppComponent implements OnInit, AfterViewInit {
userActivity;
userInactive: Subject<any> = new Subject();
constructor(
private authguardService: AuthGuardService,
private router: Router
) {
this._sidenavService.sideNavState$.subscribe((res) => {
this.onSideNavChange = res;
});
this.setSessionTimeOut();
this.userInactive.subscribe(() =>
this.logOut()
);
}
ngOnInit() {
this.debouncedRefreshUserState = this.debouncedRefreshUserState.bind(this);
}
// This will check if user is idle for 30 minutes
setSessionTimeOut() {
this.userActivity = setTimeout(
() => this.userInactive.next(undefined),
600000
);
}
// This will check if the user is inactive on Pulse window(500ms delay)
@HostListener('window:mousemove')
debouncedRefreshUserState = debounce(() => {
clearTimeout(this.userActivity);
this.setSessionTimeOut();
}, 500);
logOut() {
this.dialog.closeAll();
this.authguardService.signOut();
this.router.navigate([`/session-timeout`]);
}
}
By following these steps, you can implement a robust session timeout mechanism in your Angular application, enhancing both security and user experience.
#angular #sessiontimeout