技术:框架: 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();
}
AuthService
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都会丢失,并且用户将自动注销。
我希望用户即使刷新站点也能保持登录状态。我想念什么?
答案 0 :(得分:1)
如果您的问题是即使用户刷新后仍已登录,防护仍将用户引导至登录页面,则建议您使用AngularFireAuthGuard而不是常规的Angular防护。
您基本上可以将其实现到您的app-routing.module中,并为您处理所有事情。另外,使用此功能,您不再需要Auth-Guard-Service。
一个非常简单的例子:
进入app.module:
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