Reputation: 550
I'm succesfully using Signpost to authorize calls to protected resources in a Google account via OAuth.
However it seems a bit weird that the user has to go each and every time through Google and grant access. Is there a way of serializing the Consumer and recreating it so that re-authorization is not needed? I've tried keeping the tokens, secret and verifier in the shared preferences and setting them in the Consumer but I receive a OAuthExpectationFailedException.
Any ideas?
Upvotes: 3
Views: 1387
Reputation: 22603
Once you've received the access token, you can store it in your apps preferences like this :
provider.retrieveAccessToken(consumer, oauth_verifier);
final Editor edit = prefs.edit();
edit.putString(OAuth.OAUTH_TOKEN, consumer.getToken());
edit.putString(OAuth.OAUTH_TOKEN_SECRET, consumer.getTokenSecret());
edit.commit();
Afterwards, you can always re-create the consumer like this :
private OAuthConsumer getConsumer(SharedPreferences prefs) {
String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
OAuthConsumer consumer = new CommonsHttpOAuthConsumer(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
consumer.setTokenWithSecret(token, secret);
return consumer;
}
Once you've got the consumer, you can make API calls and the consumer will sign them.
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
consumer.sign(request);
HttpResponse response = httpclient.execute(request);
According to the signpost docs :
Signpost objects are very lightweight, so you are adviced to create an OAuthConsumer and OAuthProvider for every thread in your application that must send signed HTTP requests. Both objects are also serializable, so you can persist and restore them later.
Upvotes: 7