Android Firebase Auth: Error Fetching Token [SOLVED]
Firebase auth module has auto refresh mechanism internally. So you don’t need to care about fetching token, saving it, handling error and fetch again if expires. I am planning to create Firebase tutorial series for all modules(auth, database, storage, messaging, crash, config, ads, appindexing). That is why this blogpost is not going to be like tutorial. It is more like quick solution for people who struggled with token shit like me.
Logic is simple. When you log in to firebase auth, firebase generate token and use it to perform operation on Firebase Database. After 1 hour, token is expired and Firebase Auth SDK understand that it needs to refresh token. So token is refreshed internally. You don’t need to do anything. So what is the problem if this is that simple.
After 1 hour passed from login, I could not perform operation on my database. To do that I enable log level of FirebaseDatabase.
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
firebaseDatabase.setLogLevel(Logger.Level.DEBUG);
Than I see the problem. Lets see logcat together.
D/ConnectionRetryHelper: Scheduling retry in 398ms
D/PersistentConnection: pc_0 - Trying to fetch auth token
D/PersistentConnection: pc_0 - Error fetching token: An internal error has occured. [ Internal error. ]
D/PersistentConnection: pc_0 - Scheduling connection attempt
It was looping to fetch new fresh token. Then I googled some SO questions, firebase google groups. I found that problem is about SHA-1 Key.
You have to add SHA-1 key to Firebase Console. Otherwise your token is expired after 1 hour and not going to refresh automatically.
Getting your SHA-1 Key
There is way to get your SHA-1 key from terminal. But as an Android developer we can get it from Android Studio. Yey.
When you run signingReport, console will give you SHA-1 Key.
Copy your SHA-1 Key from output. Then go to your firebase console. Select your app settings from top left and click Project settings.
Then add your SHA-1 key to your project.
Now lets try to run app see logcat.
D/ConnectionRetryHelper: Scheduling retry in 0ms
D/PersistentConnection: pc_0 — Trying to fetch auth token
D/PersistentConnection: pc_0 — Successfully fetched token, opening connection
Yey! That’s all. I think It should be documented (I spent hours to find that problem.)
As I said, I will create a firebase modules tutorials. Follow me on medium. I will publish them here.