简体   繁体   English

即使存在 cognitoUser,Angular 路线防护也不会呈现仪表板

[英]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.我正在尝试使用 Cognito 和路由守卫保护我的 Angular 应用程序中的某些视图。 Basically what I'm trying to do is to check whether there is an active Cognito user session and if yes, load the page.基本上我要做的是检查是否有活动的 Cognito 用户会话,如果有,则加载页面。 However, even if there is a valid Cognito User, the app redirects me back to the sign-in page.但是,即使存在有效的 Cognito 用户,应用程序也会将我重定向回登录页面。 I'm a beginner in Angular, so I'm frustrated with what I have missed.我是 Angular 的初学者,所以我对我错过的东西感到沮丧。

Here is the code of canActivate function in my angular route guard.这是我的角度路线守卫中canActivate函数的代码。

  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.我已将此防护应用于app-routing.module.tsroutes数组中的某些路由,如下所示。

{ 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.非常感谢所有帮助。

So the problem was that I was not returning anything from the canActivate method.所以问题是我没有从canActivate方法返回任何东西。 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
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM