Google登录使用后端服务器进行身份验证

时间:2018-11-19 14:39:34

标签: java android google-oauth2

我需要从android应用获取访问令牌并将其发送到后端服务器,以便使用Google日历api进行一些操作。

我遵循了这一点: https://developers.google.com/identity/sign-in/android/backend-auth

但是我收到com.google.android.gms.common.api.ApiException:10 “ server_client_id”出了问题

https://console.cloud.google.com/apis/credentials中,我做了两次尝试

1)带有Web应用程序的客户端ID(我正在应用程序项目Web版本中使用它)

2),其Android应用的客户端ID根据请求报告SHA-1

正确的方法1或2是什么?为什么我会出错? 谢谢

我正在使用上面的代码:

/*GOOGLE OAUTH*/
public void signIn() {
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken("XXXXXXX.apps.googleusercontent.com")
            .requestEmail()
            .build();

    // Build a GoogleSignInClient with the options specified by gso.
    GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

    Intent signInIntent = mGoogleSignInClient.getSignInIntent();
    startActivityForResult(signInIntent, RC_SIGN_IN);

}


private void handleSignInResult(@NonNull Task<GoogleSignInAccount> completedTask) {
    try {
        GoogleSignInAccount account = completedTask.getResult(ApiException.class);
        String idToken = account.getIdToken();

        Log.v("MYLOG","Ottengo Access Token " + idToken);
        // TODO(developer): send ID Token to server and validate

        //updateUI(account);
    } catch (ApiException e) {
        Log.w("MYLOG", "handleSignInResult:error", e);
        //updateUI(null);
    }
}
/*GOOGLE OAUTH END*/

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {


    /*GOOGLE SIGN IN OAUTH SECTION*/
    // Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
    if (requestCode == RC_SIGN_IN) {
        super.onActivityResult(requestCode, resultCode, data);
        // The Task returned from this call is always completed, no need to attach
        // a listener.
        Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
        handleSignInResult(task);
    }
return;
}

1 个答案:

答案 0 :(得分:0)

我解决了这个问题,并提出了疑问。

1)不要忘记在您的应用程序根目录中放置certificate.json。

2)如果您需要后端服务器,则可以使用Web版本的凭据(例如,网站软件版本所用的凭据)(和client_id)。 不需要带有sha1指纹等的android oauth客户端ID。

3)您可以使用与网站相同的apikey,但是如果您想基于引荐来源网址(针对网站)和基于android app进行限制。您必须制作两个api密钥,一个具有引荐来源网址限制,一个具有sha1指纹限制

希望这对其他人有帮助!