Angular disable auto login
Hello,
For security reasons, I want to redirect the user to the login screen every time the application is opened. I couldn't find what to check. Thank you in advance for your help.
Replies (1)
Hi,
To redirect the user to the login screen every time the application is opened in Angular, you can use an AuthGuard. I found a couple of Stack Overflow threads that might help you resolve the issue.
The first link below suggests that you can use an AuthGuard to redirect the user to the login screen every time the application is opened. Here's an example of an existing AuthGuard:
/angular/demo1/src/app/modules/auth/services/auth.guard.ts
import { Injectable } from "@angular/core";
import { ActivatedRouteSnapshot, RouterStateSnapshot } from "@angular/router";
import { AuthService } from "./auth.service";
@Injectable({ providedIn: "root" })
export class AuthGuard {
constructor(private authService: AuthService) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const currentUser = this.authService.currentUserValue;
if (currentUser) {
// logged in so return true
return true;
}
// not logged in so redirect to login page with the return url
this.authService.logout();
return false;
}
} The second link below suggests that you can extend the RouterOutlet and when activating a route check if the user is logged in. This way you don't have to copy and paste your directive to every component. Plus redirecting based on a subcomponent can be misleading.
I hope this helps! Let me know if you have any other questions.
(1) .
(2) .
(3) .
Thanks