In this article的作者在Auth.currentAuthenticatedUser()
中使用AuthGuard
像这样:
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;
});
}
但是as noted in this issue可能会抛出错误,即使使用已通过验证并已重定向,也会导致两次重定向。第一个来自Cognito,第二个来自auth Guard,因为它不会“认为”用户已经登录。
那么我们应该调用Auth
来保证用户通过联合身份登录时不会抛出异常吗?
我认为Auth.currentSession()
可以使用,但想再次检查。
我尝试了Auth.currentSession()
,但在重定向后也无法立即提供会话。
这是我在AppComponent
中尝试过的:
Auth.currentSession().
then((s) => console.log(`The current session is ${JSON.stringify(s)}`)).
catch((e) => console.log(`There is no current session ${e}`))
应用程序加载后重定向后,将记录以下内容:
There is no current session No current user
如果我手动刷新,它将按照我们的预期记录会话。
答案 0 :(得分:0)
通常,我们似乎不认为经过身份验证的用户将在Cognito重定向后立即可用。
由于我们不能这样做,我们也不能重定向到受保护的资源,因为保护者拒绝访问。
因此,我们必须重定向到一个不受保护的页面,然后等待Amplify告诉我们已进行身份验证。
然后我们可以使用主题来通知应用程序的其他部分。
似乎正确的聆听方式(直到AngularService支持Angular 9才是)同时运行Auth.currentAuthenticatedUser()
和Hub.listen。
在重定向Auth.currentAuthenticatedUser()
之后,很可能会抛出异常,但是Hub.listen最终会发出登录事件,接下来我们可以在主题上进行
因此,尝试Auth.currentAuthenticatedUser()
并抛出它,然后尝试在sigin
块中使用Hub
监听catch
事件。在这种情况下,还要监听signout
事件。
在此之后,直到用户注销或会话超时为止,Auth.currentAuthenticatedUser()
应该始终返回用户,然后我们可以在用于观察身份验证状态的主题上进行下一步。
这就是我打算采取的方式。