Issue
I'm creating an Ionic application (iOS and Android with Capacitor). I added Firebase Auth to my application, but every time I exit the application, I need to login again.
I saw this, but there is not much documentation, and I tried it but it didn't work. I'm not sure I used it correctly or added the code in the right place. https://firebase.google.com/docs/auth/web/manage-users?hl=en
I thought about saving the user info in the local storage, and when the application loads, to check if there is data, if there is, to move the user to the home screen, otherwise, to present the login screen. But I'm not really sure if this is a good practice to do.
This is how I signing users:
async googleSignIn() {
let googleUser = await Plugins.GoogleAuth.signIn();
let credential = firebase.auth.GoogleAuthProvider.credential(googleUser.authentication.idToken);
let userCredential = await this.afAuth.signInWithCredential(credential);
return userCredential;
}
I tried using what I saw in the documentation in app.component.ts, like this:
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import firebase from 'firebase/app';
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss'],
})
export class AppComponent {
rootPage: 'login';
constructor(private router: Router) {
firebase.auth().onAuthStateChanged((user) => {
if(user) {
this.router.navigate(['home']);
} else {
this.router.navigate(['login']);
}
});
}
}
It seems like it's not "connect" to anything, but I couldn't find much info.
Solution
Firebase Authentication can automatically persist the user's authentication state, and restore it when the app is restarted/page is reloaded. But on some environments this functionality is not enabled by default, and you have to configure it yourself as shown in the documentation on auth state persistence. This should tak the form of something like:
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL)
After that your onAuthStateChanged
should start working.
Also see:
- Persistence of firebase auth on Ionic 4 App on the Ionic forums
- these results of searching for firebase auth persistennce ionic.
Answered By - Frank van Puffelen
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.