Despite having an auth guard and auth service that are functioning correctly, I encounter the issue of being logged out when attempting to access my application in a new browser tab. Each time a new tab is opened, I am prompted to log in again. Ideally, the auth service should remember my login status as long as the application is running without the need for repeated authentication. How can this behavior be modified to maintain my logged-in state across multiple tabs?
@Injectable()
export class AuthService {
private loggedIn = false;
get isLoggedIn() {
return this.loggedIn;
}
constructor(private router: Router) {
}
login(user: User) {
this.loggedIn = true;
window.localStorage.setItem('user', JSON.stringify(user));
this.router.navigate(['/vds-list']);
}
logout() {
this.loggedIn = false;
window.localStorage.clear();
this.router.navigate(['/login']);
}
}
@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild {
constructor(private authService: AuthService, private router: Router) {
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
console.log(state.url);
if (this.authService.isLoggedIn) {
return true;
} else {
this.router.navigate(['/login'], {
queryParams: {
accessDenied: true
}
});
return false;
}
}
canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return this.canActivate(childRoute, state);
}
}
The issue arises from the fact that despite having a loggedIn
variable and an isLoggedIn
method that should return true
after successful authentication once, it only works within the same tab. This discrepancy leads to AuthService#loggedIn
returning false
even though I am authenticated.