我们应该在Angular身份验证防护中使用Auth API进行哪些身份验证检查?

时间:2020-02-27 15:41:50

标签: javascript angular amazon-web-services amazon-cognito aws-amplify

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

如果我手动刷新,它将按照我们的预期记录会话。

1 个答案:

答案 0 :(得分:0)

通常,我们似乎不认为经过身份验证的用户将在Cognito重定向后立即可用。

由于我们不能这样做,我们也不能重定向到受保护的资源,因为保护者拒绝访问。

因此,我们必须重定向到一个不受保护的页面,然后等待Amplify告诉我们已进行身份验证。

然后我们可以使用主题来通知应用程序的其他部分。

似乎正确的聆听方式(直到AngularService支持Angular 9才是)同时运行Auth.currentAuthenticatedUser()和Hub.listen。

在重定向Auth.currentAuthenticatedUser()之后,很可能会抛出异常,但是Hub.listen最终会发出登录事件,接下来我们可以在主题上进行

因此,尝试Auth.currentAuthenticatedUser()并抛出它,然后尝试在sigin块中使用Hub监听catch事件。在这种情况下,还要监听signout事件。

在此之后,直到用户注销或会话超时为止,Auth.currentAuthenticatedUser()应该始终返回用户,然后我们可以在用于观察身份验证状态的主题上进行下一步。

这就是我打算采取的方式。