2
votes

The use case: I want to redirect logged in users to /dashboard, and non-logged in users to /landing.

First take:

  {
    path: '**',
    redirectTo: '/dashboard',
    canActivate: [AuthGuard],
  },
  {
    path: '**',
    redirectTo: '/landing'
  }
@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {

  constructor(private auth: AuthService, private router: Router) {}

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean|UrlTree> | Promise<boolean|UrlTree> | boolean | UrlTree {
    return this.auth.isAuthenticated$
  }
}

All users are redirected to the dashboard page.

Second try:

  {
    path: '**',
    redirectTo: '/home/loggedin',
    canActivate: [AuthGuard],
    data: { authGuard: { redirect: '/home/loggedout' } }
  },
  {
    path: '**',
    redirectTo: '/home/loggedin'
  }
@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {

  constructor(private auth: AuthService, private router: Router) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean|UrlTree> | Promise<boolean|UrlTree> | boolean | UrlTree {
    return this.auth.isAuthenticated$.pipe(
      map(loggedIn => {
        console.log(`A=${loggedIn} ${JSON.stringify(next.data.authGuard.redirect)}`)
        if (!loggedIn && next.data.authGuard.redirect) {
          return this.router.parseUrl(next.data.authGuard.redirect);
        } else {
          return false;
        }
      })
    );
  }
}

Seems like the AuthGuard is not even invoked. Possibly if I use a component instead of a redirect?

  {
    path: '**',
    component: RedirectingComponent,
    canActivate: [AuthGuard],
    data: { authGuard: { redirect: '/home/loggedout' }, redirectComponent: { redirect: '/home/loggedin' } }
  }

Now this seems to work, but it also is an awful hack.

How can AuthGuards be made to work with redirects?

2
why not redirect inside AuthGuard? - Vinaayakh
Then I would need to implement a special Guard for this use case only. And would need to specifz a dummy component just to make it work. Basically that's what I'm doind, but as I said, it's a pretty awful hack. - Ákos Vandra-Meyer
I have the same problem. I can't simply redirect inside AuthGuard as it is part of a reusable auth library; it shouldn't know where to direct to if the user is authenticated. How did you resolve this @ÁkosVandra ? - Adam Marshall
See the RedirectComponent above - Ákos Vandra-Meyer

2 Answers

0
votes

Your AuthGuard can force navigation. In your first try change the guard to something like this:

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private auth: AuthService, private router: Router) {}

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean|UrlTree> | Promise<boolean|UrlTree> | boolean | UrlTree {
    // if user is authenticated just return true;
    if (this.auth.isAuthenticated$) { return true; }

    // if user is not authenticated redirect the user and return false
    this.router.navigate(['/landing']);
    return false;
  }
}

This should redirect unauthenticated users to landing page. You can also check the example in angular docs here.

0
votes

You can achieve this using children: [] instead of setting a component (like so)

{ 
  path: '', 
  canActivate: [AuthGuard], 
  children: [] 
}