Search code examples
androidapifirebasefirebase-authenticationrestful-authentication

Android + Firebase Auth + REST API: How to properly work with token?


I'm starting a new project and Firebase Auth was the choice for authentication. The idea is to create/login users through Firebase Auth and then, use the Firebase ID Token to authenticate on my backend (through Authentication header).

In Google Samples, this is the way I should get the token:

FirebaseUser mUser = FirebaseAuth.getInstance().getCurrentUser();
mUser.getIdToken(true)
    .addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {
        public void onComplete(@NonNull Task<GetTokenResult> task) {
            if (task.isSuccessful()) {
                String idToken = task.getResult().getToken();
                // Send token to your backend via HTTPS
                // ...
            } else {
                // Handle error -> task.getException();
            }
        }
    });

But, as you can see, this is a async call, because it goes to Firebase servers to get me the Token. So, every REST API call to my backend, I need to run the above code, because I don't know when the token has expired.

Is there a better way to safety call my backend REST APIs using Firebase Auth? Or using the Firebase ID Token is the best one? If so, how should I wrap this id token get for every REST API call?

If you have a better way to authenticate users to call rest apis later, I'm all ears.


Solution

  • so the Idea is quite simple. You can use this method in the Android device as you already know:

    FirebaseUser mUser = FirebaseAuth.getInstance().getCurrentUser();
    mUser.getIdToken(true)
        .addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {
            public void onComplete(@NonNull Task<GetTokenResult> task) {
                if (task.isSuccessful()) {
                    String idToken = task.getResult().getToken();
                    // Send token to your backend via HTTPS
                    // ...
                } else {
                    // Handle error -> task.getException();
                }
            }
        });
    

    Once you hold the instance of the token you send it to your backend for authentication there, it will authenticate only once and send you backend a token that is managed by the backend itself. That's the token that will be sent in each subsequent call to the backend, not the generated by the above method.