Angular app使用firebase身份验证刷新页面时重新进行身份验证

时间:2018-03-12 16:53:59

标签: angular firebase firebase-authentication local-storage

我正在使用Firebase SDK,Angular Cli 1.5.5。

我使用firebase身份验证在Angular上构建了一个应用程序。 成功创建用户并使用电子邮件和密码登录。但每次刷新页面,我都需要再次登录。我如何使用firebase本地存储对象重新进行身份验证并将登录状态传递给CanActivate auth-guard?

auth-guard.servie 文件

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { AuthServiceService } from './auth.service';

@Injectable()
export class AuthGuardService implements CanActivate {

  constructor(private auth: AuthServiceService, private router: Router) { }
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if (this.auth.isAuthenticated()) {
      console.log(true);
      return true;
    } else {
      this.router.navigate(['/login']);
      console.log(false);
      return false;
    }
  }
}

AuthService

import { Injectable, OnInit } from '@angular/core';
import * as firebase from 'firebase';
import { Router } from '@angular/router';

@Injectable()
export class AuthServiceService implements OnInit{

  constructor(private router: Router) {}

  ngOnInit() {
  }

  signUpUser(email: string, password: string) {
    return firebase.auth().createUserWithEmailAndPassword(email, password);
  }

  signInUser(email: string, password: string) {
    return firebase.auth().signInWithEmailAndPassword(email, password);
  }

  isAuthenticated() {
    return firebase.auth().currentUser;
  }

  logout() {
   return firebase.auth().signOut();
  }
}

2 个答案:

答案 0 :(得分:0)

警卫可以返回一个Observable:

import { AngularFireAuth } from 'angularfire2/auth';

constructor(private firebaseAuth: AngularFireAuth) {}

canActivate(): Observable<boolean> {
    return this.firebaseAuth.authState.pipe(map(user => user !== null));
}

答案 1 :(得分:0)

这在身份验证卫士中对我有用。

Firebase Javascript SDK没有angularfire。

import { Injectable } from '@angular/core';
import { CanLoad, Route, UrlSegment, Router } from '@angular/router';
import { Observable, of } from 'rxjs';
import { take, tap, switchMap } from 'rxjs/operators';
import { AuthService } from './auth.service';
import * as firebase from 'firebase';
import 'firebase/auth';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanLoad {

  constructor(private authService: AuthService,
              private router: Router) {}

  canLoad(
    route: Route,
    segments: UrlSegment[]
  ): boolean | Observable<boolean> | Promise<boolean> {
    return new Promise((resolve, reject) => {
      firebase.auth().onAuthStateChanged((user: firebase.User) => {
        if (user) {
          console.log('User is logged in');
          resolve(true);
        } else {
          console.log('User is not logged in');
          this.router.navigateByUrl('/auth');
          resolve(false);
        }
      });
    });
  }

来源: https://javebratt.com/ionic-firebase-tutorial-auth/