简体   繁体   English

如何在 NGRX 中使用身份验证保护

[英]how do I use an auth guard with NGRX

I am using NGRX in an Angular app and I'm trying to use an auth guard.我在 Angular 应用程序中使用 NGRX,我正在尝试使用身份验证保护。 when the app starts, I dispatch an action that gets the auth status from the server (firebase).当应用程序启动时,我调度一个从服务器(firebase)获取身份验证状态的操作。 The issue is if I go directly to a link that is guarded by an auth guard, the default auth state is false so that gets returned and it redirects to the login page.问题是,如果我将 go 直接连接到由 auth 保护保护的链接,则默认 auth state 为 false,因此会返回并重定向到登录页面。

Here is my canActivate method这是我的 canActivate 方法

canActivate() {
        return this.store.select(fromAuth.getAuthenticatedStatus).pipe(
            //filter(isAuth => isAuth == true || isAuth == false),
            take(1),
            map((isAuth: boolean) => isAuth),
            catchError(() => of(false))
        )
    }

Is there a way to wait until the auth status comes back from the server before checking the store for the auth status?有没有办法等到身份验证状态从服务器返回,然后再检查商店的身份验证状态? I've tried filter and removing the take operator but it didn't seem like that worked.我已经尝试过过滤并删除 take 运算符,但它似乎并不奏效。

I don't want to put the call to the server in the auth guard because I don't want it to check the server every time I switch pages.我不想在身份验证守卫中调用服务器,因为我不希望它在每次切换页面时检查服务器。

There You have:你有:

@Injectable()
export class LoggedGuard implements CanActivate {

    constructor(private auth: AngularFireAuth, private router: Router) { }

    canActivate() {
        return this.auth.authState.pipe(
            take(1),
            map(user => !!user), // !! convert User object to boolean value
            tap(isLogged => {
                if(!isLogged) {
                    this.router.navigate(['/login'])
                    console.log("You are not logged in. You cannot access route.")
                }
            })
        )
    }
}

In this situation i prefer to make a request to firebase to get the fresh authentication status not taking it from store.在这种情况下,我更喜欢向 firebase 发出请求,以获得新的身份验证状态,而不是将其从商店中取出。 This is more important if You make guards for someone with some claims, because if You remove some one admin he might have still old claims.如果您为有一些声明的人设置警卫,这一点更为重要,因为如果您删除某个管理员,他可能仍然有旧的声明。

Firebase have his own IndexedDB if You connect store to some 'LocalDatabase' in browser and by mistake your app will retrieve data from local and will not check for updates You can have endless logged in user even You ban him and delete his account. Firebase 如果您将商店连接到浏览器中的某些“LocalDatabase”并且错误地您的应用程序将从本地检索数据并且不会检查更新您可以无限登录用户即使您禁止他并删除他的帐户。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM