1

I have an application with login page and dashboard. I have used AuthGuard to redirect the routeto dashboard only if token exists and valid. But when I enter URL /login it goes back to login page even if the token exists.

This is my code which I have tried;

import {
  CanActivate,
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
  Router,
} from '@angular/router';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { AuthenticationService } from './authentication.service';


@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthenticationService, private router: Router) {}

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): boolean | Observable<boolean> | Promise<boolean> {
    const isAuth = this.authService.getIsAuth();
    if (!isAuth) {
      this.router.navigate(['/login']);
    }
    return isAuth;
  }
}

app routing module

  { path: '',
    canActivate: [AuthGuard],
    component: dashboard
  },
  { path: 'signin',
    component: signin
  }

authService: Here i'm setting my isAuthenticated to false and enabling it to true when i get the access_token

 private isAuthenticated = false;

 getIsAuth() {
    return this.isAuthenticated;
  }

 return this.http.post(api, data)
      .subscribe(
        (response) => {
          if (response && response.access_token) {
            console.log(response.access_token);
            this.isAuthenticated = true;
            .......

           }
       })

9
  • might you share how does getIsAuth look like? Commented Jun 4, 2020 at 12:54
  • 1
    There isn't a route guard on the signin path, so a user will always be able to navigate to it. You could develop a route guard which only allows for unauthenticated users, and have it redirect the user to the dashboard route if they're already logged in. Commented Jun 4, 2020 at 12:55
  • @satanTime updated my code. Please have a look Commented Jun 4, 2020 at 13:01
  • @Paul Let me try that way. Commented Jun 4, 2020 at 13:02
  • 1
    better to ask him to post his comment as an answer and accept it :) ping @Paul Commented Jun 4, 2020 at 13:06

1 Answer 1

2

There isn't a route guard on the signin path, so a user will always be able to navigate to it. You could develop a route guard which only allows for unauthenticated users, and have it redirect the user to the dashboard route if they're already logged in.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.