我已经成功在我的安卓应用中实现了使用Firebase身份验证的Google登录。
如您所见,我已使用我的帐户登录,并出现在Firebase控制台上。
函数firebaseAuthWithGoogle在用户使用Google登录后对其进行Firebase身份验证:
另一个函数 firebaseAuthWithGoogle 所做的事情是:连接到 http Apache 服务器,并通过以下代码片段将用户信息保存在 MySQL 用户表 中。
我正在使用Retrofit作为http客户端,同时结合okhttp作为http请求体拦截器来记录http请求,如下所示:
当模拟器上出现Toast Text"API调用后登录失败"时,我在日志中看到了以下内容:
将此添加到清单文件中:
![enter image description here](https://istack.dev59.com/jEtQ3.webp)
函数firebaseAuthWithGoogle在用户使用Google登录后对其进行Firebase身份验证:
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mFirebaseAuth.signInWithCredential(credential)
.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(TAG, "signInWithCredential:success");
final FirebaseUser user = mFirebaseAuth.getCurrentUser();
//This is to connect to the http server and save the user data in my MySql database
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(LoginActivity.this, new OnSuccessListener<InstanceIdResult>() {
@Override
public void onSuccess(InstanceIdResult instanceIdResult) {
String userToken = instanceIdResult.getToken();
String uid = user.getUid();
String name = user.getDisplayName();
String email = user.getEmail();
String profileUrl = user.getPhotoUrl().toString();
String coverUrl = "";
UserInterface userInterface = ApiClient.getApiClient().create(UserInterface.class);
Call<Integer> call = userInterface.signin(new LoginActivity.UserInfo(uid,name,email,profileUrl,coverUrl,userToken));
call.enqueue(new Callback<Integer>() {
@Override
public void onResponse(Call<Integer> call, Response<Integer> response) {
progressDialog.dismiss();
Toast.makeText(LoginActivity.this,"Login succesfull AFTER API CALL",Toast.LENGTH_SHORT).show();
startActivity(new Intent(LoginActivity.this,MainActivity.class));
finish();
}
@Override
public void onFailure(Call<Integer> call, Throwable t) {
progressDialog.dismiss();
Toast.makeText(LoginActivity.this,"Login failed AFTER API CALL",Toast.LENGTH_SHORT).show();
}
});
}
});
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
}
// ...
}
});
}
另一个函数 firebaseAuthWithGoogle 所做的事情是:连接到 http Apache 服务器,并通过以下代码片段将用户信息保存在 MySQL 用户表 中。
//This is to connect to the http server and save the user data in my MySql database
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(LoginActivity.this, new OnSuccessListener<InstanceIdResult>() {
@Override
public void onSuccess(InstanceIdResult instanceIdResult) {
String userToken = instanceIdResult.getToken();
String uid = user.getUid();
String name = user.getDisplayName();
String email = user.getEmail();
String profileUrl = user.getPhotoUrl().toString();
String coverUrl = "";
UserInterface userInterface = ApiClient.getApiClient().create(UserInterface.class);
Call<Integer> call = userInterface.signin(new LoginActivity.UserInfo(uid,name,email,profileUrl,coverUrl,userToken));
call.enqueue(new Callback<Integer>() {
@Override
public void onResponse(Call<Integer> call, Response<Integer> response) {
progressDialog.dismiss();
Toast.makeText(LoginActivity.this,"Login succesfull AFTER API CALL",Toast.LENGTH_SHORT).show();
startActivity(new Intent(LoginActivity.this,MainActivity.class));
finish();
}
@Override
public void onFailure(Call<Integer> call, Throwable t) {
progressDialog.dismiss();
Toast.makeText(LoginActivity.this,"Login failed AFTER API CALL",Toast.LENGTH_SHORT).show();
}
});
}
});
}
当用户通过身份验证后,调用服务器失败,显然会执行此行代码:
Toast.makeText(LoginActivity.this,"Login failed AFTER API CALL",Toast.LENGTH_SHORT).show();
我正在使用Retrofit作为http客户端,同时结合okhttp作为http请求体拦截器来记录http请求,如下所示:
ApiClient.java
public static Retrofit getApiClient(){
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(httpLoggingInterceptor)
.build();
if(retrofit==null){
retrofit = new Retrofit.Builder().baseUrl(BASE_URL)
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
当模拟器上出现Toast Text"API调用后登录失败"时,我在日志中看到了以下内容:
D/OkHttp: --> POST http://10.0.2.2/friendster/public/app/login
Content-Type: application/json; charset=UTF-8
Content-Length: 413
D/OkHttp: {"CoverUrl":"","email":"MyEmail@gmail.com","name":"Ahmed Ghrib","profileUrl":"https://lh6.googleusercontent.com/-S8l_5gZaXJ8/AAAAAAI/AAAAAAAAAAA/ACHi3rfObo6-Ta-wxrMUvcAZ8Yg/s96-c/photo.jpg","uid":"YACACYYDcGVr26N8OHuTuQlQqvU2","userToken":"ecxdtFaKldI:APA91bHb1PAA5hU6i1oMqnSsDXXkAaXNb6dynyaYmhU_soHTWmLXud6REjCpqTjsGpgdBh1NMYUqAr3SaTUWapN4v73zkvyYD2f3yegUP3H38eeU_JtH7NOSMKbF4U"}
D/OkHttp: --> END POST (413-byte body)
W/e.myapplicatio: Verification of okhttp3.internal.http.ExchangeCodec okhttp3.internal.connection.RealConnection.newCodec$okhttp(okhttp3.OkHttpClient, okhttp3.Interceptor$Chain) took 134.353ms
D/OkHttp: <-- HTTP FAILED: java.net.UnknownServiceException: CLEARTEXT communication to 10.0.2.2 not permitted by network security policy
所以我发现这是导致错误的原因:
网络安全策略不允许与10.0.2.2进行CLEARTEXT通信。
在查看了StackOverflow之后,我发现需要创建这个文件:
src/main/res/xml/network_security_config.xml
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">api.example.com(to be adjusted)</domain>
</domain-config>
</network-security-config>
将此添加到清单文件中:
<application
---
android:networkSecurityConfig="@xml/network_security_config">
在使用Postman测试我的数据库后,我确定问题出在我的Android项目中。
我以为这应该解决了问题。但是,我仍然遇到完全相同的问题。在日志中仍然会出现以下错误:
网络安全策略不允许与10.0.2.2进行明文通信