加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular – 在检查用户之前,AuthGuard不会等待身份验证完成

发布时间:2020-12-17 07:56:55 所属栏目:安全 来源:网络整理
导读:我在这里阅读了指南: https://angular.io/docs/ts/latest/guide/router.html 看起来非常简单,但是,我不确定如何在auth guard(canActivate)中使用angularfire2的身份验证.我试过的是: AuthService import { Injectable } from '@angular/core';import { Ang
我在这里阅读了指南: https://angular.io/docs/ts/latest/guide/router.html

看起来非常简单,但是,我不确定如何在auth guard(canActivate)中使用angularfire2的身份验证.我试过的是:

AuthService

import { Injectable } from '@angular/core';
import { AngularFire } from 'angularfire2';

@Injectable()
export class AuthService {

  private user: any;

  constructor(private af: AngularFire) {
    this.af.auth.subscribe(user => {
      this.user = user;
    })
  }

  get authenticated(): boolean {
    return this.user ? true : false;
  }

}

AuthGuard

@Injectable()
export class AuthGuard implements CanActivate {

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

  canActivate(): Observable<boolean> | boolean {
    if (this.authService.authenticated)
      return true;

    this.router.navigate(['/login']);
    return false;
  } 

}

我还为引导程序提供程序添加了AuthService.

这种工作正常,我的主要问题是当我刷新(或最初加载)具有AuthGuard的页面时,它总是将我重定向到登录页面,因为AuthGuard不等待认证响应.有没有办法等待身份验证完成(即使它失败),然后检查用户是否经过身份验证?

问题出在你的代码上.在AuthGuard中,您检查authenticated()方法的结果,该方法很可能返回false,因为仍未设置用户属性.尝试这个:

AuthService:

import { Injectable } from '@angular/core';
import { AngularFire } from 'angularfire2';';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class AuthService {

  private user: any;

  constructor(private af: AngularFire) { }
  setUser(user) { this.user = user; }
  getAuthenticated(): Observable<any> { return this.af.auth; }
}

AuthGuard:

@Injectable()
export class AuthGuard implements CanActivate {

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

  canActivate(): Observable<boolean> | boolean {
    // here check if this is first time call. If not return 
    // simple boolean based on user object from authService
    // otherwise:

    return this.authService.getAuthenticated.map(user => {
          this.authService.setUser(user);
          return user ? true : false;
    })

  } 
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读