我与帐户管理器和OAuth-2斗争了一段时间,我已经实现了AccountManager (使用服务和帐户身份验证器)、使用webview登录活动等。当用户在webview上输入其凭据时,我实现了所有oauth-2流,并将访问令牌保存为AccountManager密码。当我对服务器执行http-请求时,我所知道的最后一件事是如何正确地实现流,它的响应是Json
{"message":"access_token_is_expired","error":true....}因此,我应该读取这个响应,分析它并使用resresh令牌执行另一个请求,以获得另一个访问令牌。如何正确地实现这一点?哪里?在哪堂课?可能我的Authenticator.getAuthToken方法应该改进吗?这是代码:
@Override
public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account,
String authTokenType, Bundle loginOptions) throws NetworkErrorException {
Log.v(TAG, "getAuthToken()");
if (!authTokenType.equals(Const.AUTHTOKEN_TYPE)) {
final Bundle result = new Bundle();
result.putString(AccountManager.KEY_ERROR_MESSAGE, "invalid authTokenType");
return result;
}
final AccountManager am = AccountManager.get(mContext);
final String auth_token = am.getPassword(account);
if (auth_token != null) {
final Bundle result = new Bundle();
result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
result.putString(AccountManager.KEY_ACCOUNT_TYPE, Const.ACCOUNT_TYPE);
result.putString(AccountManager.KEY_AUTHTOKEN, auth_token);
return result;
}
final Intent intent = new Intent(mContext, LoginActivity.class);
intent.putExtra(Const.KEY_SERVER, am.getUserData(account, Const.KEY_SERVER));
//intent.putExtra(LoginActivity.PARAM_AUTHTOKEN_TYPE, authTokenType);
intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
final Bundle bundle = new Bundle();
bundle.putParcelable(AccountManager.KEY_INTENT, intent);
return bundle;
} @Override
protected JSONObject doInBackground(Void... params) {
InputStream is = null;
try {
String url = "...";
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
String urlParameters = "access_token=" + mToken;
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
conn.connect();
int response_code = conn.getResponseCode();
is = conn.getInputStream();
String str_response = NetworkUtilities.readStreamToString(is, 500);
JSONObject response = new JSONObject(str_response);
return response;
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}我做了大量的工作来理解这一点,但我失败了。
发布于 2014-12-18 10:48:29
几天后,由于网络信息的幸运,我在github上阅读了代码,并做了一些研究。为了帮助像我这样的人:
在上面的getAuthToken方法中可以重新定义过期的令牌,但是在服务器中添加应该重命名的绑定(loginOptions)信息(例如,以"forceReauth“= true的形式),我在方法中检查这个参数,然后询问方法(上面的第二个代码和平),否则我会使用通常的流。
第二件重要的事情--我在这里看到的一行代码-- Why is AccountAuthenticator#getAuthToken() not called? 上帝保佑汤姆G (我不能给他加一票,因为我的名声很好)。在invalidateAuthToken之前,使用getAuthToken的代码行为我做了一切。如果你觉得这有用的话,给我投一票吧。
https://stackoverflow.com/questions/27491614
复制相似问题