我使用“kreait / firebase-php”在Laravel中生成Firebase自定义令牌。我生成自定义令牌的代码如下:
public function getToken(){
$user = Auth::user();
$serviceAccount=ServiceAccount::fromJsonFile(__DIR__.'/service_account.json');
$firebase = (new Factory)
->withServiceAccount($serviceAccount)
->create();
$customToken=$firebase->getAuth()->createCustomToken("id");
return response()->json(["custom_token"=>$customToken]);
}
我没有任何问题地获得JWT令牌。但是当我尝试在android中使用此令牌登录时,我得到令牌格式不正确的错误。我的Android代码如下:
firebaseAuth.signInWithCustomToken(customToken)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d("SignIn", "signInWithCustomToken:success");
FirebaseUser user = firebaseAuth.getCurrentUser();
Log.e("current User is",user.getUid());
} else {
Log.w("Sign iN failed", "signInWithCustomToken:failure", task.getException());
Toast.makeText(MainActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
/// updateUI(null);
}
}
});
Logcat输出为:
com.google.firebase.auth.FirebaseAuthInvalidCredentialsException: The custom token format is incorrect. Please check the documentation.
at com.google.android.gms.internal.zzdxm.zzao(Unknown Source)
at com.google.android.gms.internal.zzdwn.zza(Unknown Source)
at com.google.android.gms.internal.zzdxx.zzap(Unknown Source)
at com.google.android.gms.internal.zzdya.onFailure(Unknown Source)
at com.google.android.gms.internal.zzdxo.onTransact(Unknown Source)
at android.os.Binder.execTransact(Binder.java:565)
请帮我解决此错误。谢谢。
答案 0 :(得分:0)
生成的自定义令牌是Lcobucci\JWT\Token
的一个实例 - 当您将其传递给response()->json(...)
时,json()
方法尝试json_encode()
对象而不是使用其字符串表示,这是行不通的。
因此,如果要使用SDK的某个方法返回的JWT令牌的字符串表示形式,则需要将对象强制转换为字符串:
return response()->json(["custom_token" => (string) $customToken]);