Javascript 我们应该在Angular authentication Guards中使用Auth API执行什么身份验证检查?
作者在Javascript 我们应该在Angular authentication Guards中使用Auth API执行什么身份验证检查?,javascript,angular,amazon-web-services,amazon-cognito,aws-amplify,Javascript,Angular,Amazon Web Services,Amazon Cognito,Aws Amplify,作者在AuthGuard中使用Auth.currentAuthenticatedUser(),如下所示: canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree { return Auth.curren
AuthGuard
中使用Auth.currentAuthenticatedUser()
,如下所示:
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return Auth.currentAuthenticatedUser().then(() => { return true; })
.catch(() => {
this.router.navigate(['signin']);
return false;
});
}
在应用程序加载时重定向后,将记录以下内容:
There is no current session No current user
如果我手动刷新,那么它会像我们预期的那样记录一个会话。一般来说,我们可能不会假设经过身份验证的用户在Cognito重定向后立即可用 由于我们不能这样做,我们也不能重定向到受保护的资源,因为守卫拒绝访问 因此,我们必须重定向到非保护页面,然后等待Amplify告诉我们身份验证已经发生 然后,我们可以使用主题通知应用程序的其他部分 似乎正确的监听方式(直到AngularService支持Angular9)是并行运行Auth.currentAuthenticatedUser()和Hub.listen 在重定向之后,Auth.currentAuthenticatedUser()很可能会抛出,但Hub.listen最终将发出signin事件,我们可以在下一个主题中使用它 因此,请尝试
Auth.currentAuthenticatedUser()
,如果它抛出,则尝试在catch
块中使用Hub
侦听sigin
事件。在这种情况下,还要监听注销事件
在此之后,直到用户注销或会话超时,Auth.currentAuthenticatedUser()
应始终返回一个用户,我们可以在用于观察已验证状态的主题上进行下一步操作
所以这就是我计划的方法。首先,我会避免在警卫中这样做:this.router.navigate(['sign'])
。返回UrlTree
是此处的预期用途(在我看来)。
There is no current session No current user