firebase auth 在刷新时丢失 cookie

Ero*_*ano 3 google-authentication firebase firebase-authentication angular

技术:框架:Angular,组件:Ionic,Auth-Service:Firebase,NPM-Module:https : //www.npmjs.com/package/@angular/fire

情况:用户可以通过用户名和密码登录,也可以使用 Google Auth 登录。当用户登录时,一些 cookie 会存储在浏览器中。

按照这里的要求是我用来登录的代码:

登录

loginWithGoogle() {
    from(this.authService.logIn())
        .pipe(
            concatMap(() => this.authService.getAuth().signInWithPopup(new auth.GoogleAuthProvider())),
            concatMap(userCredential => this.initStateAndRoute(userCredential)),
        )
        .subscribe();
}
Run Code Online (Sandbox Code Playgroud)

认证服务

export class AuthService {

constructor(
    private fireAuth: AngularFireAuth,
) {
}

getUser(): Observable<firebase.User> {
    return this.fireAuth.user;
}

logOut() {
    return this.fireAuth.auth.signOut();
}

getAuth() {
    return this.fireAuth.auth;
}

logIn() {
    return this.fireAuth.auth.setPersistence(firebase.auth.Auth.Persistence.LOCAL);
}
Run Code Online (Sandbox Code Playgroud)

}

Auth-Guard-Service

@Injectable({
providedIn: 'root'
})
export class AuthGuardService implements CanActivate {
constructor(
    private authService: AuthService,
    private router: Router,
) {
}

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

    if (this.authService.getAuth().currentUser) {
        return true;
    }

    this.router.navigateByUrl('login');
    return false;
}
Run Code Online (Sandbox Code Playgroud)

问题:当网站刷新时,所有这些 cookie 都会丢失,用户会自动注销。

我希望用户即使在刷新站点时也能保持登录状态。我错过了什么?

Ful*_* D. 5

如果您的问题是即使用户在刷新后已登录,守卫仍将用户引导至登录页面,那么我建议使用 AngularFireAuthGuard 而不是常规的 Angular 守卫。

您基本上可以将其实现到您的 app-routing.module 中,它会为您处理一切。此外,通过使用它,您不再需要 Auth-Guard-Service。

一个非常简单的例子:

进入 app.module:

import { AngularFireAuthGuardModule } from '@angular/fire/auth-guard'; 

@NgModule({
   declarations: [],
   imports: [
      AngularFireAuthGuardModule,
   ],
   providers: [],
   bootstrap: []
})
Run Code Online (Sandbox Code Playgroud)

并进入 app-routing.module:

import { AngularFireAuthGuard, redirectUnauthorizedTo, redirectLoggedInTo } from '@angular/fire/auth-guard';

const redirectUnauthorizedToHome = () => redirectUnauthorizedTo(['home']);
const redirectLoggedInToAccount = () => redirectLoggedInTo(['my-account']);

const routes: Routes = [
  { path: 'my-account', component: MyAccountComponent, canActivate: [AngularFireAuthGuard], data: { authGuardPipe: redirectUnauthorizedToHome } },
  { path: 'create-account', component: CreateAccountComponent, canActivate: [AngularFireAuthGuard], data: { authGuardPipe: redirectLoggedInToAccount } },
];
Run Code Online (Sandbox Code Playgroud)

您可以从这里查看详细信息:https : //github.com/angular/angularfire/blob/master/docs/auth/router-guards.md