使用AccountManager令牌发出Volley请求

时间:2015-09-16 12:50:24

标签: android android-volley token accountmanager

我正在努力让Volley网络库与Android的AccountManager配合使用,我用它来获取REST API的身份验证令牌。我的基本想法是延迟实际的Volley请求(实际上是GSONRequest扩展默认值),直到从AccountManager中检索到令牌(参见下面的TokinzedGsonRequest)。但是,这似乎并没有起作用 - GC正在疯狂地工作,应用程序最终因Stackoverflow错误而崩溃。有什么想法吗?

APIClient.java

public static void makeGsonRequest(Activity context, GsonRequest request, RequestQueue requestQueue) {
    AccountManager accountManager = AccountManager.get(context);
    Account account = getAccount(context, accountManager);

    // Delay the request until a token is available
    TokenizedGsonRequest futureRequest = new TokenizedGsonRequest(request, requestQueue);

    Bundle options = new Bundle();
    accountManager.getAuthToken(
            account,
            context.getResources().getString(R.string.authenticator_auth_type),
            options,
            context,
            futureRequest,
            null
    );
}

TokenizedGsonRequest.java(实现AccountManagerCallback)

/**
 * Wrapper around {@link .helpers.GsonRequest} for use with
 * an {@link android.accounts.AccountManager}. The actual {@link com.android.volley.Request}
 * is delayed until a token has been obtained.
 */
private static class TokenizedGsonRequest implements AccountManagerCallback<Bundle> {
    public static final String TAG = TokenizedGsonRequest.class.getSimpleName();
    private GsonRequest mRequest;
    private RequestQueue mRequestQueue;

    private TokenizedGsonRequest(GsonRequest request, RequestQueue requestQueue) {
        this.mRequest = request;
        this.mRequestQueue = requestQueue;
    }

    @Override
    public void run(AccountManagerFuture<Bundle> result) {
        Bundle bundle;
        // todo authentication error
        try {
            bundle = result.getResult();
        } catch (OperationCanceledException e) {
            e.printStackTrace();
            return;
        } catch (AuthenticatorException e) {
            e.printStackTrace();
            return;
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        String authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);
        if (!TextUtils.isEmpty(authToken)) {
            Log.d(TAG, "Received authentication token " + authToken);
            try {
                // Since Volley request urls are final, we have to copy the existing one
                String tokenUrl = API.appendQueryParameter(mRequest.getUrl(), API.TOKEN, authToken);
                GsonRequest requestCopy = new GsonRequest<>(
                        mRequest.getMethod(),
                        tokenUrl,
                        mRequest.getClass(),
                        mRequest.getHeaders(),
                        mRequest.getRequestObject(),
                        mRequest.getListener(),
                        mRequest.getErrorListener() // todo wrap error listener for retry on 400
                );
                // Retain the original request tag for cancellation
                requestCopy.setTag(TAG);
                mRequestQueue.add(requestCopy);
            } catch (AuthFailureError e) {
                Log.d(TAG, e.getMessage());
                // todo bubble up
            }
        } else {
            // todo authentication error
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我自己解决了这个问题,并设法通过使用基于标头的身份验证将经过身份验证的Volley请求与AccountManager集成在一起。事实证明,使用GSON时克隆请求并不能很好地工作,因为参数化信息会丢失。

<强> APIClient.java

/**
 * Wrapper around {@link com.votilab.votiapp.helpers.GsonRequest} for use with
 * an {@link android.accounts.AccountManager}. The actual {@link com.android.volley.Request}
 * is executed when an authentication token has been obtained.
*/
public class AuthenticatedRequestCallback implements AccountManagerCallback<Bundle> {
public static final String TAG = AuthenticatedRequestCallback.class.getSimpleName();

public static final String AUTH_TOKEN_PARAM = "token";
public static final String AUTH_TOKEN_HEADER = "X-Auth-Token";

private Request mRequest;
private RequestQueue mRequestQueue;

private final AuthenticationErrorListener mErrorListener;

/**
 * Callback interface to listen for errors thrown by the
 * {@link android.accounts.AccountManager}.
 */
public interface AuthenticationErrorListener {
    public void onAuthenticationError(AuthenticatorException e);
}

public AuthenticatedRequestCallback(Request request,RequestQueue requestQueue,
                                    AuthenticationErrorListener listener) {
    this.mRequest = request;
    this.mRequestQueue = requestQueue;
    this.mErrorListener = listener;
}

@Override
public void run(AccountManagerFuture<Bundle> result) {
    Bundle bundle;
    try {
        bundle = result.getResult();
    } catch (OperationCanceledException | IOException e) {
        if (mErrorListener != null) {
            mErrorListener.onAuthenticationError(new AuthenticatorException(e.getMessage()));
        }
        return;
    } catch (AuthenticatorException e) {
        if (mErrorListener != null) {
            mErrorListener.onAuthenticationError(e);
        }
        return;
    }

    String authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);

    if (!TextUtils.isEmpty(authToken)) {
        Log.d(TAG, "Received authentication token " + authToken); // todo remove log message
        try {
            ((AuthorizableRequest) mRequest)
                    .addHeader(AUTH_TOKEN_HEADER, authToken);
        } catch (ClassCastException e) {
            throw new ClassCastException(mRequest.toString()
                    + " must implement " + AuthorizableRequest.class.getSimpleName());
        }
        // Queue the request for execution
        mRequestQueue.add(mRequest);
    } else {
        if (mErrorListener != null) {
            mErrorListener.onAuthenticationError(
                    new AuthenticatorException("Authentication token is empty."));
        }
    }
}

<强> AuthenticatedRequestCallback.java

/**
 * An interface for implementation in a {@link com.android.volley.Request} to
 * support custom authentication headers.
 */
public interface AuthorizableRequest {

    public void addHeader(String header, String value);

}

}

<强> AuthorizableRequest.java

mApiClient.makeRequest(someVolleyRequest, new AuthenticatedRequestCallback.AuthenticationErrorListener() {
                @Override
                public void onAuthenticationError(AuthenticatorException e) {
                    // something went wrong in the account manager
                }
            });

假设正确实现了扩展AbstractAccountAuthenticator的自定义Authenticator,您应该能够在您的活动中发出请求,同时在后台处理身份验证:

/
相关问题