[Django]-Authenticating Android with firebase Authentication and send token to verify to backend Django

0👍

I can’t comment about your approach. But even I want to know the best approach. Here is how I am doing it using the info provided in this page verify-id-tokens

  1. User login using firebase sdk.
  2. I attach the token as header in retrofit http call interceptor. Now the id token are only valid for 15-20 mins so you cant save them. Just use below code to add the interceptor in retrofit http call

    public class FirebaseUserIdTokenInterceptor implements Interceptor {
    
    // Custom header for passing ID token in request.
    private static final String X_FIREBASE_ID_TOKEN = "Authorization";
    
    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        Request request = chain.request();
    
        try {
            FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
            if (user == null) {
                throw new Exception("User is not logged in.");
            } else {
                Task<GetTokenResult> task = user.getIdToken(true);
                GetTokenResult tokenResult = Tasks.await(task);
                String idToken = tokenResult.getToken();
    
                if (idToken == null) {
                    throw new Exception("idToken is null");
                } else {
                    Request modifiedRequest = request.newBuilder()
                            .addHeader(X_FIREBASE_ID_TOKEN, "Bearer ".concat(idToken))
                            .build();
                    return chain.proceed(modifiedRequest);
                }
            }
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }
    

    }

  3. My node server verifies the id token and response is sent if id token is valid else error message.

Check the warning on the page:

The ID token verification methods included in the Firebase Admin SDKs
are meant to verify ID tokens that come from the client SDKs, not the
custom tokens that you create with the Admin SDKs.

Hope this helps!!

Leave a comment