Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Firebase Auth Token without using Task Listeners?

I am using Retrofit 2 and before Firebase Auth I used to store my token in SharedPreferences and in my HttpInterceptor

@Named("rest_api")
@Singleton
@Provides
Interceptor provideRESTInterceptor(final UserManager userManager) {
    return new Interceptor() {
        @Override
        public Response intercept(final Chain chain) throws IOException {
            final Request original = chain.request();

            Request request = original.newBuilder()
                    .header("Accept", "application/json")
                    .header("Authorization", "XXXX " + sharedPreference.getToken())
                    .method(original.method(), original.body())
                    .build();

            Response response = chain.proceed(request);
            return response;
        }
    };
}

How could i achieve something like this with FirebaseUser.getToken(false/true) ? I don't know how to wait for the listener callback and than process the request with firebase token.

I am also thinking to check for token validity in here and if its about to expire getToken(true)

like image 542
Bikash Avatar asked Jan 05 '23 03:01

Bikash


1 Answers

I am not sure to understand the whole problem, but to wait for the listener callback (in other words, making a synchronous method out of an asynchronous call) can be achieved like this :

private String getToken() {
    final StringBuilder token = new StringBuilder() ;
    final CountDownLatch countDownLatch = new CountDownLatch(1) ;
    FirebaseAuth.getInstance().getCurrentUser().getToken(true).addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {
        @Override
        public void onComplete(@NonNull Task<GetTokenResult> task) {
            token.append(task.getResult().getToken());
            countDownLatch.countDown();
        }
    });
    try {
        countDownLatch.await(30L, TimeUnit.SECONDS);
        return token.toString() ;
    } catch (InterruptedException ie) {
        return null;            
    }
}

Notes :

  • StringBuilder is just used here as a String holder.
  • Bullet-proof implementation should of course check task.isSuccessful()
  • Timeout (here 30 sec) should be adapted to your situation

Hope this helps.

like image 189
Benoit Avatar answered Jan 13 '23 14:01

Benoit