Angular 2 - Firebase在页面刷新时保持登录状态

Ste*_*tar 7 javascript firebase angularfire firebase-authentication angular

所以我真的很接近这个问题.基本上,我有登录工作,我有代码设置来监视onAuthStateChanged,但问题是,当我刷新页面,即使用户当前登录,它仍然重定向到/login页面,因为我有auth警卫设置,检查用户是否已登录.

我有一个auth服务设置,可以进行所有身份验证检查.

在我的auth服务构造函数中,这就是我onAuthStateChanged设置代码的地方:

constructor(
    private auth: AngularFireAuth,
    private router:Router,
    private db:AngularFireDatabase,
  ) {

    firebase.auth().onAuthStateChanged(function(user) {
     if (user) {
       // What do I need to put here to ensure that the auth guard goes to the intended route?
     }
    });

  }
Run Code Online (Sandbox Code Playgroud)

这是我的auth guard的canActivate()方法:

 canActivate(route:ActivatedRouteSnapshot, state:RouterStateSnapshot):Observable<boolean> {

      if(this.authService.getAuthenticated()) {
        return Observable.of(true);
      } else {
        this.router.navigate(['/login']);
      }
    }
Run Code Online (Sandbox Code Playgroud)

这是getAuthenticated()方法:

getAuthenticated() {
    return firebase.auth().currentUser;
  }
Run Code Online (Sandbox Code Playgroud)

更新:

以下是用户实际登录时调用的方法.在实际组件中,这是登录方法:

login(data, isValid) {
    if(isValid) {

      this.authService.login(data.email, data.password)
          .then(
              (data) => {
                console.log('data', data);
                this.router.navigate(['/projects'])
              }, error => {
                this._utilities.createToasty({
                  msg: "The email/password combination is incorrect.",
                  type: "error"
                });
              }
          );
    }
  }
Run Code Online (Sandbox Code Playgroud)

在auth服务中,这是登录方法:

login(email, password) {
    return firebase.auth().signInWithEmailAndPassword(email, password);
  }
Run Code Online (Sandbox Code Playgroud)

所以现在,我并不完全确定我需要在哪里放置哪些代码来确保当我的用户刷新页面时,auth guard会接收并实际允许用户转到路径而不是总是重定向到/login路线.

思考?

Ced*_*Ced 5

我真的不知道答案,因为我不使用firebase所以那些更多的指针

猜1:用户处于中间状态

当canActivate方法执行时,在后台运行身份验证的功能尚未运行.因此,当前用户尚未设置.我想firebase只是转到你的本地存储并检查令牌是否有效.如果它是它的功能,那么只需确保在canActivate之前发生这种情况.

但是它可以在之前运行并且当前用户仍然是未定义的,如果它是异步的,这是非常可能的.然后你必须确保canActivate在结算后运行.

实际上,更好的是:在你的can activate方法中使用observable,如下所示:

码:

 canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    return this.af.auth.map((auth) => {
        if (!auth) {
          this.router.navigateByUrl('login');
          return false;
        }
        return true;
    }).take(1);
  }
Run Code Online (Sandbox Code Playgroud)

猜猜2:你必须在本地存储中存储一些东西.

这些身份验证服务通常需要在localstorage中存储令牌,然后此令牌用于在页面刷新时对用户进行身份验证.在我能读到的内容中,这是在firebase的后台完成的.您仍然可以检查本地存储/会话存储,以确保您在那里看到信息.

如果您在localStorage/sessionStorage中没有看到任何相关内容,则可能需要在登录时输入一些内容.