Reputation: 3281
I have a client/server game (iOS client, Java server) in which player accounts are tied to email addresses. The client allows sign-in with Google, Facebook and Twitter, using their respective sign-in SDKs.
To prevent clients from spoofing the wrong email address, I validate the oauth tokens by sending them over SSL to the server side, and using the user's credentials to validate that they do indeed own that email address.
For Google and Facebook, token validation (and fetching the associated email) was a pretty straightforward REST call. But Twitter requires you to create a signed request, which turns out to be complex and error-prone. Fortunately there is an open-source client library, twitter4j, which enabled me to do it in just a few lines of code.
Figuring out how to use twitter4j for this task was a bit tricky, so I'm documenting it here.
Upvotes: 0
Views: 352
Reputation: 3281
You'll need these imports:
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
When you sign up your app for Twitter API access, they provide you a consumer API key and a consumer API secret to identify your iOS app. You will need these available on your Java server somehow. It is easiest to put them directly into the source code:
String consumerApiKey = "arglebarglearglebargle"; // oauth_consumer_key
String consumerApiSecret = "tHiSisas3cReTc0nSUm3rAp1Keypr0v1d3Dbytw1tt3r";
Then you need your oauth credentials sent over from the iOS app:
String accessToken = "myUs3rs0aUthAcc355t0k3n";
String accessTokenSecret = "sdflkjasdflkjasdlfkjasdlfkjasldkfjlasdkfjldf";
Configure twitter4j with your credentials:
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerApiKey);
builder.setOAuthConsumerSecret(consumerApiSecret);
builder.setOAuthAccessToken(accessToken);
builder.setOAuthAccessTokenSecret(accessTokenSecret);
builder.setIncludeEmailEnabled(true);
Configuration config = builder.build();
TwitterFactory factory = new TwitterFactory(config);
Twitter twitter = factory.getInstance();
Now you can make Twitter API calls via the Twitter object. In my case, I make a single call to verify the oauth credentials and fetch the user's email so I can check it against the player database:
twitter4j.User user = twitter.verifyCredentials();
String email = user.getEmail();
...
Upvotes: 2