当前位置: 首页 > 知识库问答 >
问题:

Angular canActivate重定向到浏览器上的登录刷新Firebase

解河
2023-03-14

angularfire2和firebase的Angular5身份验证应用程序。该应用程序使用应用程序内链接导航效果良好。但是,如果我点击浏览器刷新,它会将我重定向回登录页面。即使是true,allowed也总是返回False,因为我成功登录了firebase。

AuthInfo

export class AuthInfo {  
    constructor(public $uid: string) {}

    isLoggedIn() {
        // console.log(this.$uid);
        return !!this.$uid;
    }
}

AuthService

import { Injectable } from '@angular/core';
// tslint:disable-next-line:import-blacklist
import {Observable, Subject, BehaviorSubject} from 'rxjs/Rx';
import {AngularFireAuth } from 'angularfire2/auth';
import { AuthInfo } from '../security/auth-info' ;
import {Router} from '@angular/router';
import * as firebase from 'firebase/app';

@Injectable()
export class AuthService {
  static UNKNOWN_USER = new AuthInfo(null);
  authInfo$: BehaviorSubject<AuthInfo> = new BehaviorSubject<AuthInfo>(AuthService.UNKNOWN_USER);

  constructor(private afAuth: AngularFireAuth, private router: Router) {}
    login(email, password): Observable<AuthInfo> {
        return this.fromFirebaseAuthPromise(this.afAuth.auth.signInWithEmailAndPassword(email, password));
    }

    // signUp(email, password) {
    //  return this.fromFirebaseAuthPromise(this.afAuth.auth.createUserWithEmailAndPassword(email, password));
    // }

    fromFirebaseAuthPromise(promise): Observable<any> {
        const subject = new Subject<any>();
        promise
              .then(res => {
                    const authInfo = new AuthInfo(this.afAuth.auth.currentUser.uid);
                    this.authInfo$.next(authInfo);
                    subject.next(res);
                    subject.complete();
                    // console.log(res);
                },
                err => {
                    this.authInfo$.error(err);
                    subject.error(err);
                    subject.complete();
                });
        return subject.asObservable();
    }

    logout() {
        this.afAuth.auth.signOut();
        this.authInfo$.next(AuthService.UNKNOWN_USER);
        this.router.navigate(['/login']);
    }
    refresh() {
        const url = window.location.href;
    } 
}

AuthGuard

import {tap, take, map} from 'rxjs/operators';
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router} from '@angular/router';
// tslint:disable-next-line:import-blacklist
import {Observable} from 'rxjs/Rx';
import {Injectable} from '@angular/core';
import {AuthService} from '../security/auth-service';
import { Location } from '@angular/common';
import { auth } from 'firebase';
import { log } from '@firebase/database/dist/src/core/util/util';

@Injectable()
export class AuthGuard implements CanActivate {
    redirectUrl: string;
    currentURL= '';
    constructor(private authService: AuthService, private router: Router) {}

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

        // tslint:disable-next-line:no-unused-expression
        console.log(this.authService.authInfo$);

        return this.authService.authInfo$.pipe(
            map(authInfo => authInfo.isLoggedIn()),
            take(1),
            tap(allowed => {
                if  (!allowed) {
                    console.log(allowed);
                     this.router.navigate(['/login']);
                }
            }),
        );
    }
}

共有1个答案

咸琪
2023-03-14

使用UNKNOWN\u USER初始化authInfo$,这将始终使第一个激发的值不为真,重新加载时,您只取第一个值,这是默认值。

一种解决方案是在防护装置中使用的可观察值中,使第一个值为null,并过滤null值:

AuthService

...
new BehaviorSubject<AuthInfo>(null);
...

AuthGuard

...
return this.authService.authInfo$.pipe(
  filter(_ => _ !== null),
  map(authInfo => authInfo.isLoggedIn()),
  take(1),
...

这样,只有对警卫有意义的值才会被激发。

 类似资料:
  • 我在我的Angular 5应用程序中使用keycloak JavaScript适配器,虽然我的登录和重定向工作,但问题是每当我刷新我的ng应用程序时,它会再次要求keycloak登录,尽管我看到我的会话仍然在 /auth/realms/{image a领域名称}/帐户上处于活动状态。 正如我从KeyClope JS适配器文档中了解到的那样https://www.keycloak.org/docs/

  • 我正在将DNN应用程序从07.00.02升级到07.03.04并在安装后将所有门户重定向到登录页面。所有门户都配置有一个登陆页面,该页面被配置为允许“所有用户”角色视图访问。还有人在升级后遇到过这个问题吗? 2015-02-05 05:45:01 127.0.0.1 GET/-80-127.0.0.1 Mozilla/5.0+(Windows+NT+6.3;+WOW64)+AppleWebKit/

  • When webpack-dev-server is running it will watch your files for changes. When that happens it rebundles your project and notifies browsers listening to refresh. To trigger this behavior you need to ch

  • 记录器文件中的日志- org.springframework.Security.Access.event.loggerlistener-安全授权失败,原因是:org.springframework.Security.Access.accessdeniedexception:访问被拒绝;通过身份验证的主体:org.springframework.security.authentication.ano

  • 问题内容: 我一直在寻找解决方案,但无论尝试如何,似乎都无法正确解决。 成功登录后,应该将用户重定向到他来自的页面,假设他一直在浏览帖子,并且想要登录以便可以发表评论,因此应该将他重定向到他正在浏览的帖子。所以这是我所拥有的: login.php 显示登录表单: 在 登录-check.php 检查用户名和传球被输入,的确用户存在,或者如果他已经登录,并且参数发送给login.php中: 然后将参数

  • 问题内容: 我正在尝试建立一个简单的网站,其登录功能与SO上的登录功能非常相似。用户应该能够以匿名用户的身份浏览网站,并且每个页面上都会有一个登录链接。当单击登录链接时,用户将被带到登录表单。成功登录后,应将用户带回到他首先单击登录链接的页面。我猜想我必须以某种方式将当前页面的url传递给处理登录表单的视图,但是我真的无法使其正常工作。 编辑:我想通了。我通过将当前页面作为GET参数传递来链接到登