我正在实现 android 帐户身份验证器,到目前为止,我可以添加帐户获取令牌等。问题是当我更改凭据服务器端时。
如果凭据更改,我无法从服务器收到通知,因此我的下一个 API 请求将被拒绝,因为令牌不再有效。
请求被拒绝后,可能有 2 个原因 -> 令牌已过期或凭据不再有效
发生这种情况时,我使保存的令牌无效并调用 getAuthToken()
在我的 getAuthToken() 中,我首先尝试请求新令牌,如果它被拒绝意味着凭据不再可用,因此我需要提示登录活动。问题是 AccountAuthenticatorResponse.onError 似乎只能记录错误,仅此而已。我尝试使用 AccountAuthenticatorResponse.onResult 传递带有 KEY_INTENT 的捆绑包进行登录活动,但它没有做任何事情。有什么想法吗?
@Override
public Bundle getAuthToken(final AccountAuthenticatorResponse authenticatorResponse, final Account account,
final String authTokenType, Bundle bundle) throws NetworkErrorException {
//Get the account manager to access the account details
final AccountManager accountManager = AccountManager.get(mContext);
String authToken = accountManager.peekAuthToken(account, authTokenType);
//If auth token is null then try to log in the user with the stored credentials
//It could be that previous token has expired
if (authToken == null) {
final String password = accountManager.getPassword(account);
final String clientID = accountManager.getUserData(account, CLIENT_ID_KEY);
final String apiSecret = accountManager.getUserData(account, API_SECRET_KEY);
final String serverUrl = accountManager.getUserData(account, SERVER_ADDRESS_KEY);
if (password != null && clientID != null && apiSecret != null && serverUrl != null) {
Logger.log(LOG_TAG, "Requesting new token...", Log.VERBOSE);
ApiRequestManager.getInstance(mContext)
.getToken(serverUrl, clientID, apiSecret, account.name, password,
new NetworkCallBack() {
@Override
public void tokenReceived(Token JsonToken) {
//Credentials still valid, token received
//Returning data back to the account authenticator
Bundle result = new Bundle();
result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
result.putString(AccountManager.KEY_AUTHTOKEN, JsonToken.getAccess_token());
authenticatorResponse.onResult(result);
}
@Override
public void errorReceivingToken(VolleyError errorResponse) {
//If we are here with error 400 it only means credentials have changed
//I should prompt LogIn activity at this point
if (errorResponse.networkResponse.statusCode == 400) {
Bundle loginActivityBundle =
promptLoginActivity(authenticatorResponse, account.type, authTokenType, null);
//authenticatorResponse.onResult(loginActivityBundle); authenticationatorResponse.onError(errorResponse.networkResponse.statusCode, "error");
}
}
});
return null;
}
}
//If we got an authToken return the account and login info in a bundle
if (authToken != null) {
Bundle result = new Bundle();
result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
return result;
}
//If we are here then means either we do not have an account signed
//or credentials are no longer valid -> prompt login procedure again
return promptLoginActivity(authenticatorResponse, account.type, authTokenType, null);
}