angularamazon-cognitoangular2-routingangular-route-guards

Angular route guard doesn't render dashboard even if a cognitoUser is present


I'm trying to protect some views in my Angular app using Cognito and route guards. Basically what I'm trying to do is to check whether there is an active Cognito user session and if yes, load the page. However, even if there is a valid Cognito User, the app redirects me back to the sign-in page. I'm a beginner in Angular, so I'm frustrated with what I have missed.

Here is the code of canActivate function in my angular route guard.

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    
        var poolData = {
          UserPoolId: environment.cognitoUserPoolId, 
          ClientId: environment.cognitoAppClientId
        };
  
        var userPool = new CognitoUserPool(poolData);
        var cognitoUser = userPool.getCurrentUser(); // could console.log the user without problem
        
        if (cognitoUser != null) {
          cognitoUser.getSession((err: any, session: any) => {
            if (err) {
              alert(err.message || JSON.stringify(err));
              return;
            }
            
            console.log('session validity: ' + session.isValid());
            const isSessionValid = session.isValid();
            console.log(isSessionValid) // this also get printed as 'true'
            if (!isSessionValid) {
              // redirect the user
              this.router.navigate(['signin']); // but this is fired
            }
            return isSessionValid;
          });
        }
        this.router.navigate(['signin']); //maybe this also get fired ?
        return false
  }
  
}

I have applied this guard to some routes in the routes array of my app-routing.module.ts as follows.

{ path: 'sessions', component: SessionsComponent,canActivate: [AuthGuard] },
{ path: 'dashboard', component: DashboardComponent,canActivate: [AuthGuard] },

Can someone kindly point me out a way to fix this problem so that the auth flow goes smoothly? All help is highly appreciated.


Solution

  • So the problem was that I was not returning anything from the canActivate method. Changing it to the following fixed the problem.

    canActivate(
        route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree  {
            var isAuth = false; // new variable to keep the auth status
    
            var poolData = {
              UserPoolId: environment.cognitoUserPoolId, 
              ClientId: environment.cognitoAppClientId
            };
      
            var userPool = new CognitoUserPool(poolData);
            var cognitoUser = userPool.getCurrentUser();
            
            if (cognitoUser != null) {
              cognitoUser.getSession((err: any, session: any) => {
                if (err) {
                  alert(err.message || JSON.stringify(err));
                  return;
                }
                
                isAuth = session.isValid(); // assigning auth status inside the callback
              })
            }
            if(!isAuth) {
              this.router.navigate(['signin'])
            }
            return isAuth; // return isAuth
      }