gpt4 book ai didi

angular - firebase auth 在刷新时丢失 cookie

转载 作者:行者123 更新时间:2023-12-04 12:41:06 25 4
gpt4 key购买 nike

技术:框架: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();
}

授权服务

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);
}

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;
}

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

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

最佳答案

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

您基本上可以将它实现到您的 app-routing.module 中,它会为您处理所有事情。此外,使用它您不再需要 Auth-Guard-Service。

一个非常简单的例子:

进入应用程序模块:

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

@NgModule({
declarations: [],
imports: [
AngularFireAuthGuardModule,
],
providers: [],
bootstrap: []
})

并进入 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 } },
];

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

关于angular - firebase auth 在刷新时丢失 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59111407/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com