Reputation: 955
I have created an auth guard like below based on the auth token from local storage. If the token is not present in local storage, it is working and redirecting the user back to the login page. But if the token is present in storage then I still can go to the login page.
Question: If the token is present in storage then a user will not be able to route back to the login page.
Guard.ts
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
):
| Observable<boolean | UrlTree>
| Promise<boolean | UrlTree>
| boolean
| UrlTree {
const isLoggedIn = this._spotify.isAuthenticated();
if (isLoggedIn) {
// authorised so return true
return true;
}
// not logged in so redirect to login page with the return url
this._logger.error('Not authenticated, redirecting...');
this._router.navigate(['/'], {
queryParams: { returnUrl: state.url }
});
return false;
}
Auth Service
isAuthenticated(): boolean {
if (localStorage.getItem('accessToken')) {
return true;
}
return false;
}
Upvotes: 0
Views: 1531
Reputation: 87
If you have some route like so
{ path: '/login', component: LoginComponen}
you can add a new authGuard for it specifically
export class LoginGuard implements CanActivate {
constructor(private _spotify: AuthService, private router: Router) {}
canActivate(): Observable<any> {
const isLoggedIn = this._spotify.isAuthenticated();
if (!isLoggedIn) {
return true;
}
return this.router.navigate(['/'])
}
and then add it to your route
{ path: '/login', component: LoginComponent, canActivate: [LoginGuard] }
Upvotes: 1