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.
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();
...
Related
I am working on app engine endpoints (back end), i have created credentials for ios, web application and others, client id and Client secret are generated (same id are added as part of endpoint code ). Now i assume app engine endpoint requests are authorized by oauth from the IOS and when call it from api-explorer. My questions are
When endpoints are tested through api-explorer, without client id i am able to get success response. Is it something i need to do, so that oauth is the first level of security always ?
#Api(name = "myapp", version = "v1", description = "myapp cloud-endpoint",
clientIds = {Constants.WEB_CLIENT_ID, Constants.IOS_CLIENT_ID})
public class YourFirstAPI {
How to give client id and Client secret from IOS client while consuming app engine endpoints ?
Please help me on this.
Endpoints auth is optional. If you need to require auth, currently you need to inject the User parameter into your API methods and check them manually. For example,
public void apiMethod(User user) {
if (user == null) {
throw new UnauthorizedException();
}
...
}
I suggest you check out the Rest iOS client docs.
My goal is to read the user's Google profile and email data (plain Gmail accounts, not a Google+ account, if the user does not have one) on my server with OAuth2.
I have used the following guidelines:
Google+ Sign-In for server-side apps
Migrating to Google+ Sign-In
Quick-start sample app for Java
Finally, I now have a GoogleTokenResponse Java object on my server that I could use to read the profile and email data from the Google server... if I only knew how.
What is the cleanest way of doing this in Java with the Google Java API(s)?
Ok, it was pretty obvious in the end, but it took me a while to bridge the gap between sorting out the OAuth2 stuff to get the tokenResponse as in the sample app, and then actually reading data from a Google API.
In my case, the key was to find the Javadoc for Google+ API in Google APIs Client Library for Java. Then the rest was easy:
GoogleCredential cred = new GoogleCredential().setFromTokenResponse(tokenResponse);
Plus plus = new Plus.Builder(TRANSPORT, JSON_FACTORY, cred)
.setApplicationName(APPLICATION_NAME).build();
Person person = plus.people().get("me").execute();
List<Emails> emails = person.getEmails();
String name = person.getDisplayName();
String emailAddr = emails.get(0).getValue();
How can I get twitter email Id on my web site.
I am using twitter4j api.
But while getting email it shows
Email: Twitter does not provide this!
In twitter4j api no method available to get email
user = twitter.showUser(twitter.getId());
twitterUser = new TwitterUser(user.getId(),user.getName(),user.getScreenName(),user.getLocation(),
user.getDescription(),user.getProfileImageURL().toString(),
user.getFollowersCount(),user.getFriendsCount(),user.getFavouritesCount(),user.getStatusesCount(),
user.getListedCount(),user.getCreatedAt().toString(),user.getTimeZone(),user.getUtcOffset(),
user.getLang(),user.getURL()!=null?user.getURL().toString():null);
Is there any way to get this.
Is there any othe api to get email and /FirstName/LastName .
Please suggest any solution for this.
Twitter does not provide an API for email retrieval. From their FAQ:
How do I obtain a user's email address?
If you'd like a user's email address, you'll need to ask a user for it within the confines of your own application and service. The Twitter API does not provide the user's email address as part of the OAuth token negotiation process nor does it offer other means to obtain it.
If you have a user's ID or screen name, you can get any additional information from the Twitter4J User interface.
EDIT: Originally this question asked how I could authenticate with the Google Analytics API using only my API key. As vlatko pointed out, this isn't possible. Now I'm just focused on getting OAuth2 to work. I will be trying vlatko's suggestions when I get a chance and will update the question. In the meantime, feel free to contribute answers with anything you think I'm missing.
ORIGINAL QUESTION:
I'm trying to make requests to the Google Analytics API. I'm walking through the Hello Analytics tutorial trying to replicate the steps. Whatever I try, I can't seem to authenticate succesfully.
The tutorial says the following:
Open the file you created named HelloAnalyticsApi.java and add the
following method:
private static Analytics initializeAnalytics() throws Exception {
// Authorization.
Credential credential = OAuth2Native.authorize(
HTTP_TRANSPORT, JSON_FACTORY, new LocalServerReceiver(),
Arrays.asList(AnalyticsScopes.ANALYTICS_READONLY));
// Set up and return Google Analytics API client.
return Analytics.builder(HTTP_TRANSPORT, JSON_FACTORY)
.setApplicationName("Google-Analytics-Hello-Analytics-API-Sample")
.setHttpRequestInitializer(credential)
.build();
}
When a user encounters this script, the application will attempt to
open the default browser and navigate the user to a URL hosted on
google.com. At this point, the user will be prompted to login and
grant the application access to their data. Once granted, the
application will attempt to read a code from the browser window, then
close the window.
The difference is that I'm trying to do this with a servlet application, and I want to use simple API access with an API key (rather than an OAuth 2.0 client ID). I know that OAuth 2.0 is recommended, but I only need to access data that I own and want to simplify the technical requirements. I based this decision on this page, which says:
An API key is a unique key that you generate using the Console. When
your application needs to call an API that's enabled in this project,
the application passes this key into all API requests as a key={API_key}
parameter. Use of this key does not require any user action or
consent, does not grant access to any account information, and is not
used for authorization.
If you are only calling APIs that do not require user data, such as
the Google Custom Search API, then API keys may be simpler to
implement. However, if your application already uses an OAuth 2.0
access token, then there is no need to generate an API key as well. In
fact, Google ignores passed API keys if an OAuth 2.0 access token is
already associated with the corresponding project.
I can't find many code examples of auth flow just using the API key - most everything I've found shows using the client ID with the downloaded .p12 file, for example the GoogleCredential javadoc. The one example application I could find was Google's Books Sample app. Anyway, here's what I tried (mimicking the first request in the tutorial, which gets a list of the accounts from the management API):
Analytics analytics =
new Analytics.Builder(httpTransport, jsonFactory, null)
.setApplicationName("Dev API Access")
.build();
Management.Accounts.List list =
analytics.management().accounts().list().setKey(apiKey);
Accounts accounts = list.execute();
Where "Dev API Access" is the "Name" field in my API console dashboard. The API key is a server key restricted to my IP address. This fails with the following response:
401 Unauthorized
{
"code": 401,
"errors": [
{
"domain": "global",
"location": "Authorization",
"locationType": "header",
"message": "Login Required",
"reason": "required"
}
],
"message": "Login Required"
}
I also tried this:
Analytics analytics =
new Analytics.Builder(httpTransport, jsonFactory, null)
.setApplicationName("Dev API Access")
.setGoogleClientRequestInitializer(new AnalyticsRequestInitializer(apiKey))
.build();
Management.Accounts.List list = analytics.management().accounts().list();
Accounts accounts = list.execute();
Which shows the same error. What am I doing wrong here? Is OAuth2 required for analytics calls? If so, why does just using the API key work in the Books Sample app?
Moving on, I went ahead and tried OAuth2 anyway - I created a client ID and downloaded the .p12 private key file. But I couldn't get that working either. Here's what I tried:
Credential credential =
new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(serviceAccountId)
.setServiceAccountScopes(AnalyticsScopes.ANALYTICS_READONLY)
.setServiceAccountPrivateKeyFromP12File(new File(p12FilePath))
.setServiceAccountUser(serviceAccountUser)
.build();
Analytics analytics =
new Analytics.Builder(httpTransport, jsonFactory, credential)
.setApplicationName("Dev API Access")
.build();
Management.Accounts.List list = analytics.management().accounts().list();
Accounts accounts = list.execute();
Where serviceAccountId is the email address of the Google account owning the project and serviceAccountUser is the email address listed on the generated client ID. This fails with the following:
400 Bad Request
{
"error": "invalid_grant"
}
What does "invalid grant" mean, and how do I successfully authenticate (ideally without OAuth2)?
To answer your first question: in general, OAuth2.0 is used for authorized access to user's private data, so getting user consent and obtaining an access token is required. In the case with Google Books API, however, if you're accessing public data, there is no need for end user consent so an API key is sufficient. If you try accessing non public data with the Books API, you'll still need an OAuth2 token.
The good news for your case is that even with OAuth2, you can bypass user involvement and streamline your flow with Service Accounts - assuming your application has access to the API. There is a way to set that up for the Analytics API, explained here (check the steps in the Service Accounts section). I think you are on the right track with your Credential builder, but I don't think you need to set the service account user in there, since you are not doing any user impersonation.
vlatko's answer got me on the right track. The issue turned out to be that I was confusing the owner email address with the service account email address. For example, I was doing the following:
Credential credential =
new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId("owneremail#gmail.com") //wrong
.setServiceAccountScopes(AnalyticsScopes.ANALYTICS_READONLY)
.setServiceAccountPrivateKeyFromP12File(new File(p12FilePath))
.setServiceAccountUser("xxx#developer.gserviceaccount.com") //unnecessary
.build();
When I needed to do this:
Credential credential =
new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId("xxx#developer.gserviceaccount.com")
.setServiceAccountScopes(AnalyticsScopes.ANALYTICS_READONLY)
.setServiceAccountPrivateKeyFromP12File(new File(p12FilePath))
.build();
Also, I had added owneremail#gmail.com as a user on my Analytics application - this similarly needed to be the service account email instead.
How can I authenticate programmatically to Google?
Now that ClientLogin (https://developers.google.com/accounts/docs/AuthForInstalledApps)
is deprecated, how can we perform a programmatic authentication to Google with OAuth2?
With ClientLogin we could perform a post to
https://www.google.com/accounts/ClientLogin
with email and password parameters and obtain the authentication token.
With OAuth2 i can't find a solution!
#
My app is a java background process.
I saw, following this link: developers.google.com/accounts/docs/OAuth2InstalledApp#refresh, how to obtain a new access token using a refreshed token.
The problem is that I can't find a java example about how to instantiate an Analytics object (for example) to perform a query when I have a new valid access token
This is my code that returns a 401 Invalid credentials when invoke the "execute()":
public class Test {
static final String client_id = "MY_CLIENT_ID";
static final String client_secret = "MY_SECRET";
static final String appName = "MY_APP";
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
private static final JsonFactory JSON_FACTORY = new JacksonFactory();
static String access_token = "xxxx";
static String refreshToken = "yyyyy";
public static void main (String args[]){
try {
GoogleCredential credential =
new GoogleCredential.Builder()
.setTransport(HTTP_TRANSPORT)
.setJsonFactory(JSON_FACTORY)
.setClientSecrets(client_id, client_secret).build();
credential.setAccessToken(access_token);
credential.setRefreshToken(refreshToken);
//GoogleCredential
Analytics analytics = Analytics.builder(HTTP_TRANSPORT, JSON_FACTORY)
.setApplicationName(appName)
.setHttpRequestInitializer(credential)
.build();
Accounts accounts = analytics.management().accounts().list().execute();
} catch (Exception e) {
e.printStackTrace();
}
}
What is the problem?
Check the OAuth 2 flow for Installed Application:
https://developers.google.com/accounts/docs/OAuth2InstalledApp
It still requires the user to authenticate with a browser the first time, but then you can store the refresh token and use it for subsequent requests.
For alternative solutions, check the Device flow or Service Accounts, they are explained in the same documentation set.
I found the Google Java client to be overly complex and poorly documented. Here's plain and simple Servlet example with Google Oauth2. For a background process you'll need to request access_type=offline. As others have mentioned you need the user to do a one time authorization. After that you can request refresh tokens as google tokens expire in an hour.
Although I appreciate that the OP was originally targeting the OAuth2InstalledApp approach, I would like to point out a working solution using the OAuth2WebServer approach. They don't differ significantly and this worked for me. I have found the google OAuth library to be pretty good as it will handle most of the OAuth dance for you and it makes it easy to refresh the access token. The solution below depends on using a pre-obtained refresh token.
As the accepted answer states, to get OAuth authentication working (even for a Java background process) where the request relies upon access to user data
requires the user to authenticate with a browser the first time, but then you can store the refresh token and use it for subsequent requests.
From previous comments by the OP I see the following
So I followed OAuth2 for Web Server Applications (here offline access is documented) but I have still problems.
1) I perform the first request via browser and I obtain autenticaton code for offline access
2) I perform a java post of the authentication code and obtain acces token and refresh token
The approach I used is more like
1) I perform the first request via a browser and obtain the refresh token for offline access
2) In java I provide the refresh token to the library and the library will obtain the access token etc
specifically, using the google-api-java-client library the code is quite straightforward and note that I haven't set an access token as the OP did, as I am calling credential.refreshToken(); elsewhere. (I check if I have a valid access token already and if not call refresh prior to the API call)
private Credential generateCredentialWithUserApprovedToken() throws IOException,
GeneralSecurityException {
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
InputStreamReader inputStreamReader =
new InputStreamReader(jsonFileResourceForClient.getInputStream());
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(jsonFactory, inputStreamReader);
return new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory)
.setClientSecrets(clientSecrets).build().setRefreshToken(REFRESH_TOKEN);
}
Note this covers step 2 of my approach, and the REFRESH_TOKEN mentioned in step 1 can be obtained as explained below.
First there is a prior set up of a web app creating an OAuth 2.0 client ID on the Google console for Credentials where you end up with a downloaded json file which will be read into the GoogleClientSecrets object.
i.e.
Make sure you add the Google playground callback uri into Authorized redirect URIs
Then you have your client id and the client secret ready for the playground and you can also download the json which you can pull into your Java code.
The REFRESH_TOKEN is obtained by sending a request to the google oauth playground with the following configuration. Note that prior to Step 1 and selecting your scope you should go to settings to check that you are providing you own credentials and add your client id and secret just below that
Note that the Access type is Offline, which corresponds to this.
There is also a nice explanation on grabbing the refresh token here https://www.youtube.com/watch?v=hfWe1gPCnzc
That is enough to get going and is a one time set up!
Regarding refresh tokens you should be aware of their lifecycle as discussed in the docs here
In the oauthplayground you will see this
but on point 4 of the docs here it says this
Hmmm.
Also for reference see How do I authorise an app (web or installed) without user intervention? (canonical ?)
For applications that authenticate on behalf of themselves (i.e., to another application, traditionally by signing into a role account using a shared password), the OAuth2 alternative to ClientLogin offered by Google is Service Accounts:
https://developers.google.com/accounts/docs/OAuth2ServiceAccount