Firebase令牌身份验证错误



我正在使用firebase存储上传文件,但是当我上传时,我得到这个错误

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

我谷歌了一下,但找不到答案!

我想你在上传文件之前没有签名。在启动器活动的onCreate()中,尝试以下代码

FirebaseAuth mAuth = FirebaseAuth.getInstance(); 

然后在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);
            }
        });
}

这可能会解决你的问题

注意:首先在您的firebase项目中启用匿名登录。身份验证→登录方法

我也面临同样的问题,这是因为默认情况下firebase只允许从已经过身份验证的用户上传文件。

在storage util异常上面可能有类似这样的日志:

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

我们有自己的身份验证过程而不使用firebase,所以我们决定更改firebase控制台的存储规则。

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

注意:更改规则将允许任何用户上传文件到您的firebase云服务器

也许你只是无法"get started" to firebase。我这么说是因为我创建了一个项目,通过Android Studio IDE连接到firebase存储,但我必须在控制台上手动"开始"。

以下步骤对我有效:

  1. 生成正确的google服务。

  2. 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. 确保在构建中添加了以下依赖项。Gradle(项目根目录)

    dependencies {
    classpath 'com.android.tools.build:gradle:2.2.3'
    classpath 'com.google.gms:google-services:3.0.0'
    }
    
  4. 在您的活动中下载文件时添加以下代码:

    // 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());
            }
        }
    

您必须先登录FirebaseAuth。

你可以匿名登录,

但是如果你想登录用户的Google id,试试这样。

为了方便使用,我创建了一个管理器类。


  1. 创建(你的)GoogleUserManager类

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()
    }
}
  • 初始化应用程序中的管理器

  • class YourApplication : Application() {
        ...
        override fun onCreate() {
            super.onCreate()
            initGoogleUserManager()
        }
        ...
        private fun initGoogleUserManager() {
            YourGoogleUserManager.init(this)
        }
    }
    
  • 在你的Fragment(or Activity)中使用manager

  • 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())
            }
        }
    }
    

    它可以是像互联网连接一样简单的东西,如果你所有的代码都是正确的,并且你已经在firebase上验证了所有用户

    相关内容

    • 没有找到相关文章

    最新更新