【发布时间】:2013-07-29 20:23:29
【问题描述】:
我正在尝试使用 Java 在 android 设备上获取访问令牌。
首先,我在Google API Console 中为已安装的应用程序(Android)创建了客户端ID,并设置了将请求访问令牌的包,以及SHA1 fingerprint。
正如我在OAuth2ForDevices 中读到的,要获得访问令牌,我首先必须获得一个用户代码。所以我尝试使用 Aquery 发送带有 client_id 和范围的 POST 请求,如下所示:
AQuery aq = new AQuery(activity);
aq.ajax("https://accounts.google.com/o/oauth2/device/code?" +
"scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile" +
"client_id=xxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com",
JSONObject.class,new AjaxCallback<JSONObject>(){
@Override
public void callback(String url, JSONObject traffic_flow, AjaxStatus status) {
publishProgress(traffic_flow.toString());
}
});
问题是JSONObject traffic_flow 始终为空。我也尝试过使用它(但我不认为这是正确的方法):
authToken = GoogleAuthUtil.getToken(activity, mEmail, "audience:server:client_id:xxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com");
其中 mEmail 是来自 android 设备的电子邮件,但我收到了 GoogleAuthException“未知”。如何正确获取用户码?
编辑:
我终于能够使用这个获得一个身份验证令牌:
String scope = "audience:server:client_id:xxxxxxxxxxxx.apps.googleusercontent.com";
String token = GoogleAuthUtil.getToken(activity, client.getAccountName(), scope);
其中 scope 是在 Google API Console 中生成的 Web 应用程序的客户端 ID(之后我将令牌发送到我的网站并对其进行验证),客户端是 PlusClient(更多信息在 Getting started with Google+ 中)。
我已经在我的测试应用程序中获得了令牌,现在的问题是当我想将代码包含到我的新应用程序中时,我又遇到了那个丑陋的异常:
com.google.android.gms.auth.GoogleAuthException: Unknown at com.google.android.gms.auth.GoogleAuthUtil.getToken(Unknown Source)
这些应用程序的所有客户端 ID 都在同一个项目中,清单中的权限应该没问题 (GET_ACCOUNTS,USE_CREDENTIALS,AUTHENTICATE_ACCOUNTS,INTERNET,ACCESS_NETWORK_STATE)。我在新应用程序中所做的唯一更改是在创建 PlusClient 时设置范围,因为没有它它就无法工作(不知道为什么它在我的测试应用程序中没有它工作)
mPlusClient = new PlusClient.Builder(this, this, this)
.setVisibleActivities("http://schemas.google.com/AddActivity")
.setScopes(Scopes.PLUS_LOGIN, Scopes.PLUS_PROFILE)
.build()
我错过了什么?
【问题讨论】:
-
大约 2 周前,我花了一天时间让 Google Coordinate API 工作,遗憾的是,我的代码在我的工作笔记本电脑上,直到星期四我才能使用。我似乎记得这篇文章让我朝着正确的方向前进; blog.tomtasche.at/2013/05/google-oauth-on-android-using.html 祝你好运!我会喜欢这个问题,以便在我可以访问代码时提醒我签到。
-
@Robadob 谢谢你的文章,我试试看:)
-
确保您的范围字符串采用
oauth2:https://www.googleapis.com/auth/glass.timeline https://www.googleapis.com/auth/userinfo.profile的形式,我记得这是我的问题之一。 -
您不会通过这种方式获得访问令牌,而是获得用户代码和设备代码。此流程适用于输入能力有限的设备。你能确认这是否是你的要求吗?
-
该文档适用于资源/输入受限的设备,例如键盘受限的控制台等。如果您只想使用 OAuth2 并在用户进行 OAuth 流程后获取访问令牌,则应使用标准 Google 登录developers.google.com/+/mobile/android/getting-started
标签: java android oauth-2.0 access-token google-oauth