我在我的 android 应用中使用 GooglesignInClient 来验证用户身份,同时请求使用范围访问 Blogger 和授权代码。
这是代码
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.requestServerAuthCode(getString(R.string.web_client_id))
.requestScopes(new Scope("https://www.googleapis.com/auth/blogger"))
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
signInButton = findViewById(R.id.sign_in_button);
signInButton.setSize(SignInButton.SIZE_STANDARD);
signInButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
});
用户成功登录后,我得到一个授权码
GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(getApplicationContext());
String auth_code = acct.getServerAuthCode(); // it gives code like 4/0Ay0e-g5p.....
现在还是没有问题。 但是现在怎么用这个授权码来换取access-token和refresh-token呢?
我看过一些 Stackoverflow code 并做到了这一点。
String TOKEN_URL = "http://www.googleapis.com/oauth2/v4/token";
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new FormEncodingBuilder()
.add("grant_type", "authorization_code")
.add("client_id", String.valueOf(R.string.web_client_id))
.add("client_secret", "[my client serect code]")
.add("code",auth_code)
.add("redirect_uri","") //which uri should I give here since it is an android app?
.add("id_token",idToken)
.build();
Log.e(TAG, "requestbody is setted");
final com.squareup.okhttp.Request request = new com.squareup.okhttp.Request .Builder().header("content-type","application/x-www-from-urlencoded").url(TOKEN_URL).post(requestBody).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
Log.e(TAG, "onFailure: " + e.toString());
}
@Override
public void onResponse(Response response) throws IOException {
Log.e(TAG, "onResponse: " + response.toString());
}
});
当我运行这个应用程序时,我收到了 403 错误。这是我的错误日志
Response{protocol=http/1.1, code=403, message=Forbidden, url=http://www.googleapis.com/oauth2/v4/token}
这里我使用的是网络服务器类型的 OAuth 2.0 客户端 ID,因为我需要一个客户端机密,但也为 android 创建了 OAuth 2.0 客户端 ID,并提供了包名称和 SHA-1 密钥。 现在我的疑问是
请帮助我的人... 提前致谢。