Giridhar Karnik
Giridhar Karnik

Reputation: 2372

Handling Firebase IdToken expiration on Android app

As of now the Firebase IDToken obtained by

FirebaseAuth.getInstance().getCurrentUser().getIdToken(true)...

expires each hour. I am using this token to validate REST calls made to my backend system as advised here.

Currently I have an OKHttp interceptor to refresh the token every time my API confirms that the token has expired. This seems ugly and inefficient.

Is there a better way?

I used this as reference to implement this feature.

Upvotes: 2

Views: 979

Answers (2)

ooCHURIoo
ooCHURIoo

Reputation: 191

like it's said here and in the firebase doc getIdToken(false) renew the token only if it is expired.

Upvotes: 2

Kathan Shah
Kathan Shah

Reputation: 1755

You can store a timestamp in the preference storage

If its null or it has elapsed 58 or 59 minutes from current time get idToken again and shoot that in request headers, store current time again in preference storage.

if it's not null and has not elapsed 58 minutes from the current time you can use the stored idToke from preference storage which you would have stored in the previous call.

private void authorizeGet(){
        boolean valid = true;
        String idToken = PreferenceUtil.getPref(getContext()).getString(PreferenceKeys.ID_TOKEN,"");
        long timestamp = PreferenceUtil.getPref(getContext()).getLong(PreferenceKeys.ID_TOKEN_EXPIRATION,-1);

        if (idToken.isEmpty()){
            valid = false;
        }
        else{
            long diff = timestamp - TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
            if (diff<100){
                valid = false;
            }
        }

        if (valid){
            loadData(idToken);
        }
        else{
            if (mAuth.getCurrentUser()!=null){
                mAuth.getCurrentUser().getIdToken(true).addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {
                    @Override
                    public void onComplete(@NonNull Task<GetTokenResult> task) {
                        if (task.isSuccessful()){
                            PreferenceUtil.getPref(getContext()).edit().putString(PreferenceKeys.ID_TOKEN,task.getResult().getToken()).apply();
                            PreferenceUtil.getPref(getContext()).edit().putLong(PreferenceKeys.ID_TOKEN_EXPIRATION,task.getResult().getExpirationTimestamp()).apply();
                            loadData(task.getResult().getToken());
                        }
                    }
                });
            }
        }
    }

Hope this helps!

Upvotes: 0

Related Questions