简体   繁体   中英

firebase auth losing cookies on refresh

Technologies : Framework: Angular , Components: Ionic , Auth-Service: Firebase , NPM-Module: https://www.npmjs.com/package/@angular/fire

Situation : The user can login by username and password or by using Google Auth. When the user is logged in, then some cookies are stored in the browser.

As requested here is the code I use to log in:

Login

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

Problem : When the website gets refreshed, then all those cookies are lost and the user is automatically logged out.

I want the users to stay logged in even when they refresh the site. What am I missing?

If your problem is that the guard directing user to login page even though they are logged in after refresh, then I recommend using AngularFireAuthGuard instead of a regular Angular guard.

You can basically implement this into your app-routing.module and it handles everything for you. Also, with using this you don't need the Auth-Guard-Service anymore.

A very simple example:

into app.module:

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

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

and into 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 } },
];

You can look at the details from here: https://github.com/angular/angularfire/blob/master/docs/auth/router-guards.md

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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