Reputation: 105
I am using Firebase realtime database and Firebase phone auth in an android project, being developed in java.
I have been able to successfully authenticate the user with phone login, now i have set some ValueEventListeners in the databse helper. However after about one hour (as the firebase auth token expires), my value even listener callbacks are not trigerring.
How can i handle that situation. I would like to keep my users authenticated unless they manually logout.
public void refreshUserAuthToken(){
try {
FirebaseUser thisUser = FirebaseAuth.getInstance().getCurrentUser();
thisUser.getIdToken(true).addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {
@Override
public void onComplete(@NonNull Task<GetTokenResult> task) {
if (task.isSuccessful()){
// nothing
// the task is succesful
}
else {
startActivity(new Intent(getApplicationContext(), LoginActivity.class));
}
}
})
}
catch (Exception e){
// new Intent(MainActivity.class, this)
}
}
When and how should I call this? I tried using it in login activity but the task is always unsuccesful
Also should i call this function everytime an activity is loaded?
I also have the application interacting with a webservice, how can i leverage that? can someone point me to a git repo or provide me with a code flow that can help me keep my users logged in for a long time?
Thanks in advance
Edit
I changed the getIdToken(true) to getIdToken(false) which is not causing it to fail always.
This somewhat solves my purpose, however i am still not sure how and where to call it, if a user keeps an activity / fragment open for more than one hour.
the next stage is that my firebase realtime database gets internally logged out as it seems, but how to pass this new token ?
Calling this function over and over again, will definitely take me to the login page if the token times out, but how can i keep the firebase callbacks logged in?
Upvotes: 1
Views: 476
Reputation: 317740
However after about one hour (as the firebase auth token expires), my value even listener callbacks are not trigerring.
That's fully expected. ID tokens last for an hour (for security reasons), then the Firebase Auth SDK will refresh it. You will need to use that new token and use that in future requests.
You can find out when the token is refreshed by listening to changes using the provided API. You will need to use addIdTokenListener() to register an IdTokenListener that gets called whenever there is an update. For example:
FirebaseAuth.getInstance().addIdTokenListener(new FirebaseAuth.IdTokenListener listener() {
public void onIdTokenChanged (FirebaseAuth auth) {
// get the new token
auth.getCurrentUser().getIdToken(false).addOnCompleteListener // and so on...
}
});
Be sure to remove the listener when you no longer need it.
Upvotes: 2