Firebase Token Authentication error

30,571

Solution 1

I think you didn't sign before uploading files. In onCreate() of launcher activity, try this code

FirebaseAuth mAuth = FirebaseAuth.getInstance(); 

Then in onStart(),

FirebaseUser user = mAuth.getCurrentUser();
if (user != null) {
  // do your stuff
} else {
  signInAnonymously();
}

signInAnonymously()

private void signInAnonymously() {
    mAuth.signInAnonymously().addOnSuccessListener(this, new  OnSuccessListener<AuthResult>() {
            @Override
            public void onSuccess(AuthResult authResult) {
                // do your stuff
            }
        })
        .addOnFailureListener(this, new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception exception) {
                Log.e(TAG, "signInAnonymously:FAILURE", exception);
            }
        });
}

This may solve your problem

Note: Initially enable anonymous sign-in in your firebase project. Authentication -> Sign-in method

Solution 2

I was facing the same issue and it was caused because by default firebase will only allow uploading files from user's that have been authenticated.

Above the storage util exception there might be a log similar to this:

E/StorageUtil: error getting token java.util.concurrent.ExecutionException: com.google.android.gms.internal.zzajb: Please sign in before trying to get a token.

We had our own authentication process without using firebase so we decided to change the storage rules in firebase console.

service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
    allow read, write;
    }
  }
}

Note: Changing the rules will allow any user to upload files to your firebase cloud server.

Solution 3

You must first sign in to FirebaseAuth.

You can sign in anonymously,

but if you want to sign in user's google id, try like this.

I created a manager class for ease of use.


  1. Make (Your)GoogleUserManager class

object YourGoogleUserManager {

    private lateinit var gso: GoogleSignInOptions
    private lateinit var firebaseAuth: FirebaseAuth

    fun init(context: Context) {
        firebaseAuth = FirebaseAuth.getInstance()
        gso = GoogleSignInOptions
            .Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(context.getString(R.string.default_web_client_id))
            .build()
    }

    fun startGoogleSignInForResult(
        fragment: Fragment,
        onSuccess: (AuthResult) -> Unit,
        onFail: (Exception) -> Unit
    ): ActivityResultLauncher<Intent> {
        return fragment.registerForActivityResult(
            ActivityResultContracts.StartActivityForResult()
        ) {
            val task = GoogleSignIn.getSignedInAccountFromIntent(it.data)
            handleGoogleSignInResult(task, onSuccess, onFail)
        }
    }

    fun signIn(
        activityResultLauncher: ActivityResultLauncher<Intent>,
        activity: Activity
    ) {

        val googleSignInClient = GoogleSignIn.getClient(activity, gso)

        activityResultLauncher.launch(googleSignInClient.signInIntent)
    }

    private fun handleGoogleSignInResult(
        task: Task<GoogleSignInAccount>,
        onSuccess: (AuthResult) -> Unit,
        onFail: (Exception) -> Unit
    ) {
        try {
            val account = task.getResult(ApiException::class.java)
            val credential = GoogleAuthProvider.getCredential(account?.idToken, null)
            firebaseAuth.signInWithCredential(credential)
                .addOnSuccessListener {
                    CatHolicLogger.log("success to firebase google sign in")
                    onSuccess(it)
                }
                .addOnFailureListener {
                    CatHolicLogger.log("fail to firebase google sign in")
                    onFail(it)
                }
        } catch (e: ApiException) {
            CatHolicLogger.log("fail to firebase google sign in")
            onFail(e)
        }
    }

    fun signOut() {
        firebaseAuth.signOut()
    }
}
  1. Initialize manager in your application.

class YourApplication : Application() {

    ...

    override fun onCreate() {
        super.onCreate()

        initGoogleUserManager()
    }

    ...

    private fun initGoogleUserManager() {
        YourGoogleUserManager.init(this)
    }
}
  1. Use manager in your Fragment(or Activity)

class YourFragment : Fragment() {

    ...
    ...

    private val startGoogleSignInForResult =
        YourGoogleUserManager.startGoogleSignInForResult(this, onSuccess = {
            // your job after success to sign in
        }, onFail = {
            // your job after fail to sign in
        })

    ...
    ...

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.signInButton.setOnClickListener {
            YourGoogleUserManager.signIn(startGoogleSignInForResult, requireActivity())
        }
    }
}

Solution 4

Maybe you just can't "get started" to firebase. I saying that because I created a project, connect to firebase storage by Android Studio IDE, but I have to "get started" manually on console.

Solution 5

Below steps worked for me:

  1. Generated proper google-services.json from firebase with package ID

  2. In build.gradle(app)

     dependencies {
    
     compile 'com.google.firebase:firebase-storage:10.2.0'
     compile 'com.google.firebase:firebase-auth:10.2.0'
     compile 'com.google.firebase:firebase-core:10.2.0'
     compile 'com.google.firebase:firebase-database:10.2.0'
     compile 'com.firebase:firebase-client-android:2.4.0'
     }
    
  3. Make sure you add below dependencies in build.gradle(project root folder)

    dependencies {
    
    classpath 'com.android.tools.build:gradle:2.2.3'
    classpath 'com.google.gms:google-services:3.0.0'
    
    }
    
  4. While downloading file in your activity add following code:

    // Declaration reference
    private StorageReference storageRef;
    
    
    private void downloadImageFromFireBase()
    {
    showProgressDialog("Downloading image..");
    
    storageRef = storage.getReferenceFromUrl("gs://XXX.appspot.com/").child("av"+ datePassed +".jpg");
    showImageFromFireBaseDataBase();
    }
    
    private void showImageFromFireBaseDataBase()
    {
        try {
            final File localFile = File.createTempFile("images", "jpg");
            final Bitmap[] bitmap = new Bitmap[1];
                storageRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
                        Log.e("Test", "success!");
                        bitmap[0] = BitmapFactory.decodeFile(localFile.getAbsolutePath());
                        raysImage.setImageBitmap(bitmap[0]);
                    }
                }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception exception) {
                        Log.e("Test", "fail :( " + exception.getMessage());
                    }
                });
            }catch(IOException e){
            Log.e("ImageView",e.toString());
            }
        }
    
Share:
30,571
Chatrapati Shiva
Author by

Chatrapati Shiva

Updated on January 28, 2022

Comments

  • Chatrapati Shiva
    Chatrapati Shiva over 2 years

    I am using firebase storage to upload files , but when I upload I am getting this error

    E/StorageUtil: error getting token java.util.concurrent.ExecutionException: com.google.android.gms.internal.zzand: Please sign in before trying to get a token.
    

    I googled it but couldn't get answer for it! I have signed in, in firebase.