我一直在关注这两个教程:
https://developers.google.com/identity/sign-in/android/sign-in
https://developers.google.com/identity/sign-in/android/backend-auth
我设法将google登录系统集成到我的Android应用程序中,但是当我尝试获取令牌ID时,我会得到null。
当我尝试使用以下代码时:
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.server_client_id))
.build();
我在用户登录时失败。当我打电话时:
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
我无法检索令牌。
我尝试将此代码合并为:
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.requestIdToken(getString(R.string.server_client_id))
.build();
但没有任何成功。
这是我的代码:
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
// [START onActivityResult]
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
}
}
// [END onActivityResult]
// [START handleSignInResult]
private void handleSignInResult(GoogleSignInResult result) {
Log.d(TAG, "handleSignInResult:" + result.isSuccess());
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
mStatusTextView.setText(getString(R.string.signed_in_fmt, acct.getDisplayName()));
updateUI(true);
String idToken = acct.getIdToken();
if (idToken != null) {
Log.d("TOKEN", idToken);
} else {
Log.d("TOKEN", "CHUUUUUUJ WIELKI!");
}
} else {
// Signed out, show unauthenticated UI.
updateUI(false);
}
}
答案 0 :(得分:4)
Google API使用OAuth 2.0协议进行身份验证和 授权。 Google支持常见的OAuth 2.0方案,例如 那些用于Web服务器,已安装和客户端应用程序。
首先,从Google获取OAuth 2.0客户端凭据 开发人员控制台。然后您的客户端应用程序请求访问 来自Google Authorization Server的令牌,从中提取令牌 响应,并将令牌发送到您想要的Google API 访问。有关使用OAuth 2.0的交互式演示 Google(包括使用您自己的客户端凭据的选项), 尝试使用OAuth 2.0 Playground。