【问题标题】:AngularFireAuth redirect issue with angular routing guardAngularFireAuth重定向问题与角度路由保护
【发布时间】:2019-05-26 08:42:18
【问题描述】:

尊敬的 stackoverflow 社区,

我有以下问题。我尝试将 FirebaseAuthentication 与 Angular7 一起使用,并尝试使用警卫保护路线,因此只有登录用户才能访问 /profile url。

我的登录 (login.component.ts) 看起来像这样。首先,我导入 AngularFireAuth 并将其用于通过 Google、Facebook 或电子邮件登录。在 ngOnInit 方法中,我订阅了 authState 以便我可以重定向到用户。这一切都很好。

在下一步中,我想为 /profile url 编写一个 AuthGuard,这样只有登录的用户才能访问他们的个人资料。未登录的用户应该首先被重定向到/login。

我的 AuthGuard (auth.guard.ts) 看起来像这样,并且正在使用一个类 AuthService (auth.service. ts) 内部。这个 AuthService 被注入并提供了一个方法 isAuthenticated。如果用户通过了身份验证,他应该看到他的个人资料,否则 AuthGuard 应该返回 false 并将他重定向到登录。

AuthService 看起来像这样,如果用户登录,它的方法 isAuthenticated 应该返回 true,否则返回 false。

如果我没有在函数末尾添加这个虚拟对象 return true,他也会在我登录时将我重定向回 /login。他还告诉我函数没有返回值

所以我知道这个订阅在 isAuthenticated 方法中是不够的,但我很好奇检测用户是否登录的最佳解决方案是什么样的。

如果你们中的一个人有最佳实践类型的解决方案,如果他能告诉我,那就太好了。那里没有很多合适的教程。

与此同时,我将尝试继续在谷歌上寻找解决方案。我希望你们中的某个人可以帮助我解决这个问题。谢谢你:)

最好的问候 一月

【问题讨论】:

    标签: angular firebase firebase-authentication angular-router-guards


    【解决方案1】:

    订阅无法返回值。

    您可以使用地图而不是订阅。

    return this.afAuth.authState.pipe(map((res) => {
       if (res && res.uid)
          return true;
    
       return false;
    });
    

    还将isAuthenticated Method的返回值签名从boolean更改为Observable<boolean>或Observable<boolean> | boolean

    【讨论】:

      【解决方案2】:

      我已经使用 Angular FireAuth 来实现与您相同的功能,这就是我想出的:
      Function isAuthenticated ie isLoggedIn

      public isLoggedIn() {
          return this.afAuth.authState.pipe(first()).toPromise();
      }
      

      在我的保护下:

      auth.guard.ts

      canActivate (next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
          return this.auth.isLoggedIn().then((value) => {
              if (value) {
                  return true;
              } else {
                  this.router.navigate(['./login']);
                  return false;
              }
          });
      }
      

      希望对你有所帮助;)


      编辑
      我使用这些教程来更好地理解如何使用 AngularFireAuth: https://angularfirebase.com/tag/authentication/

      在你的情况下,你有这个: https://angularfirebase.com/lessons/router-guards-to-redirect-unauthorized-firebase-users/

      【讨论】:

        猜你喜欢
        • 2020-02-26
        • 1970-01-01
        • 2019-10-31
        • 1970-01-01
        • 2014-11-10
        • 2017-01-31
        • 1970-01-01
        • 1970-01-01
        • 2017-08-15
        相关资源
        最近更新 更多