Monday, 4 August 2014

Detect whether users have uploaded a profile picture to Google+

Very short post on a small feature that I know will be a popular one with some people! A regular feature request has been the ability to determine whether the profile picture with a Google+ profile is the default blue head or not. You can do that right now with the people.get API calls - and you can try it yourself from that page using the explorer.

The change is that under the "image" key you'll see an "isDefault" value. For my user you can see it's false:

"image": {
  "url": "https://lh6.googleusercontent.com/.../photo.jpg?sz=50",
  "isDefault": false
 },

But for this blue head user, it's true:

"image": {
  "url": "https://lh3.googleusercontent.com/.../photo.jpg?sz=50",
  "isDefault": true
 },

Hopefully this should make it easier to determine whether to use the profile picture from Google+ when people sign in to your apps.Client libraries might take some time to be regenerated, but its certainly available in the API right now.

Wednesday, 18 June 2014

Google Sign In with Server Side Auth on iOS

The release today of version 1.7 of the Google+ iOS SDK added the ability to authorise both a client and server for access to Google APIs. This has been a feature for Android and Web based sign-ins for a while, and now is available across all three platforms. This should simplify server side code for people who have been building cross platform apps - for example if you need to retrieve profile information on the client, but retrieve circles on a server for a friend finding feature.

The implementation for iOS is fairly straightforward. When setting up authentication, simply specify the client ID of your server on on the GPPSignIn object. This should be a client ID from the developer console which is used by your server-side code, and should be part of the same console project as your iOS client ID. For those that have done it, this is the same parameter used when retrieving an ID token:

You can see that the first part of the client ID (the project number) is the same, but the other part varies. If you try and exchange a code generated for one client ID using a different client ID you'll get an invalid_client error, even if both client IDs are part of the same project. When the user is signed in via [GPPSignIn authenticate] you can retrieve the code parameter from the GPPSignIn instance as part of the auth callback:

You can send this parameter to your server exactly as you would with one from Javascript or Android. When exchanging, be sure to not set a redirect uri in the server side auth configuration or you will get back a HTTP 400 error "redirect_uri_mismatch" from the token POST call. The exchange should always result in a refresh token (unlike with the web), so be sure to store that safely in a database or other persistent store if you're using it.

If the user is seamlessly signed in via a call to trySilentAuthentication, you won’t receive a code to use. Instead of forcing the user to sign in again with authenticate (and swap out to the browser or Google+ app to consent again) when you’re establishing a session with the server, try sending across an ID token and checking whether the server already has a refresh token for that user - this will mean a smoother experience for the user in most cases.

Thursday, 6 March 2014

Migrating Away From Userinfo

As part of the move to full OpenID connect support recently, the "userinfo" scopes and endpoint were deprecated and scheduled for shutdown in September 2014. If you are using the userinfo API endpoint to retrieve email address or profile information for a Google user, now is the time to change! Luckily, it's just a few minutes of work to move from the userinfo API to the people.get API for most people, and wont affect users at all.

What should you do?

  1. Check whether you're using userinfo
  2. Update scopes
  3. Replace userinfo API call with a call to plus.people.get

Are you using the endpoint?

Look for the section in your code where you retrieve the user's profile or email address. If you make the API call directly, you may see a URL like "https://www.googleapis.com/oauth2/v1/userinfo". The "v1" might also be "v2" as there are a couple of different versions of the api, but if it has /oauth2 then you're using the userinfo endpoint. If you're using a client library, look for using the (somewhat confusingly named) OAuth2 service or API. For example:

PHP: new Google_Service_Oauth2($client);
Python: service = build('oauth2', 'v2', http=http)
Java: oauth2 = new Oauth2.Builder(httpTransport, JSON_FACTORY, credential).build();

All of these are indicative of retrieving the user data from the userinfo API, and will need to be changed before September 2014.

What scopes should you use?

https://www.googleapis.com/auth/userinfo.profile and https://www.googleapis.com/auth/userinfo.email can be seamlessly replaced with the shorter strings profile and email. These are aliases, so they wont require the user to reconsent if they've already give access. If you're thinking about a larger change, check out my earlier post about choosing a sign in scope.

What API should you call?

All profile information for Google users is now served from the people.get API. This works for users whether or not they have a Google+ profile. It returns data in a slightly different format to the userinfo API, so you may have to change your code a little, but all the same data is available. A call to retrieve the users name, picture and email address would look like this in PHP (and should be analogous with any of the client libraries).

You can actually try the call direct from the "Try It" section at the bottom of the API page to see what the returned data looks like.

What if you want to make the smallest code change possible?

If you aren't using a client library, and don't want to change the parsing you're using, you can call the special getOpenIdConnect method, which returns data in the same format as userinfo. The only difference needed then is looking for the "sub" field rather than "id" (this was a spec change made during the development of OpenID Connect). Take a look at the differences between the calls to the API below

Userinfo API response

https://www.googleapis.com/oauth2/v1/userinfo?access_token=ya29.1.AA...
{
 "id": "104824858261236811362",
 "email": "ian@example.com",
 "verified_email": true,
 "name": "Ian Barber",
 "given_name": "Ian",
 "family_name": "Barber",
 "link": "https://plus.google.com/+IanBarber",
 "picture": "https://lh6.googleusercontent.com/-DXmOngLN6Gc/AAAAAAAAAAI/AAAAAAAAGc4/Roeci0EovY8/photo.jpg",
 "locale": "en-GB"
}
openIdConnect API response:
https://www.googleapis.com/plus/v1/people/me/openIdConnect?access_token=ya29.1.AA>...
{
 "kind": "plus#personOpenIdConnect",
 "sub": "104824858261236811362",
 "name": "Ian Barber",
 "given_name": "Ian",
 "family_name": "Barber",
 "profile": "https://plus.google.com/+IanBarber",
 "picture": "https:https://lh6.googleusercontent.com/-DXmOngLN6Gc/AAAAAAAAAAI/AAAAAAAAGc4/Roeci0EovY8/photo.jpg?sz=50",
 "email": "ian@example.com",
 "email_verified": "true",
 "locale": "en-GB"
}

In both cases, you do get a fair bit less than using the people.get API, so I would strongly recommend using people.get where possible!

There are a lot more tips on migrating to the newer sign-in options on the auth migration page, and of course if you have any questions drop into the StackOverflow tags for google-plus and google-oauth.

Tuesday, 18 February 2014

Migrating from PlusClient to GoogleApiClient

Version 4.2 of Google Play Services introduced a new replacement for PlusClient, GoogleApiClient. While PlusClient is still present, it will be removed in a future version so its a good idea to upgrade when possible. The new class has been designed based on feedback from developers across various Google Play services APIs, and provides a much more consistent, powerful base.

PlusClient was reasonably straightforward for developers implementing just Google+ Sign-In. Unfortunately, anyone looking to combine multiple services together quickly realised that managing a series of callbacks for all the different connections was way too painful. GoogleApiClient solves that by providing one central client to connect or disconnect. It allows multiple APIs to be added to a connection for Google+, Drive, Games, and the other services available.

Replacing PlusClient with GoogleApiClient isn’t too hard, and if you are using multiple clients makes life gets a lot easier - you don’t have to worry about what order to start clients in, and a much more consistent and simple workflow for calls to different services.

Building the client

The GoogleApiClient should be constructed in precisely the same place as the old PlusClient was, using GoogleApiClient.Builder. Instead of the builder taking the listener objects for the ConnectionCallbacks and OnConnectionFailedListener as constructor arguments (which usually lead to this, this, this as arguments), these are now passed in separate methods. Only the context is still passed as a constructor argument, and the others can be omitted if they aren't needed for that particular connection.

A bigger change is that each individual service has to be requested by calling addApi on the builder. No scopes will be requested by default, so most services will need a call to addScope as well. Because more than one addScope can be chained, we can avoid worrying about space separating a big string of scopes. Our basic GoogleApiClient setup to replace a straightforward PlusClient integration would look like this:

As you might guess, we’ll need to update the types of the connection failed and callbacks interfaces: GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener. You may have noticed that the onDisconnected callback is now slightly more clearly named as onConnectionSuspended. Whatever the name, this still indicates the binding to Google Play services is no longer active.

Other than that we call connect and disconnect in exactly the same way as before, such as in our onStart/onStop methods:

With the onConnectionFailed we save and resolve a ConnectionResult exactly as we would have with PlusClient. The difference is that once resolved this will connect all client services at once.

Retrieving Friends

The way to work with result sets has changed, as we can see if we look at retrieving the visible collection of friends. The new interface is much more consistently applied across the different APIs, so once you get used to it here you'll find it a familiar pattern with whichever Google service you use next. Rather than all the methods sitting on the client class, they've been divided into logical APIs, such as Plus.PeopleApi. Each method takes a GoogleApiClient as the first argument, which is used to execute the call.

The interesting thing is that we have a couple of options on what to do with the PendingResult that comes back. The old PlusClient offered a listener interface which we could implement, and the same thing can be applied with the result here.

However we can also call await on the response to get the result back in a synchronous fashion. This can be much easier if we know we will hit a point where we cannot continue without the result, and are working off the UI thread. In both cases we can test whether the call was a success by calling the getStatus method on the result, and then retrieve a buffer for the collection to iterate over as normal. Its important we close the buffer at the end.

Note: you must have enabled the Google+ API in the developer console, or you’re likely to get back a status of Status{statusCode=NETWORK_ERROR, resolution=null}.

The really cool side effect of the pending result is that we can make the call before the client is connected! If we put the loadVisible call in the onCreate and set up a callback, we’ll be pinged back as soon as the user has signed in. Because this and the other feature are part of PendingResult rather than being dependent on the API, these methods can be applied to almost any call exposed through the new Play services model, whichever product they're for.

App Activities

Reading App Activities is pretty much the same as the People example, so should be an easy port. Writing has become a little bit simpler, but we need to make sure to request the proper types of App Activity when creating the connection to ensure the user grants us permission to write them. The old addActions method is no more, so the activity type should be passed to the addApi method as in a second parameter. This will be familiar to anyone that has used GoogleAuthUtil to request offline access, except with a custom object instead of a Bundle.

The App Activity types are now set as separate strings, rather than one space separated one. We pass the resulting options object as the (optional) second parameter to our addApi call to the GoogleApiClient.Builder.

Writing app activities is pretty straightforward, but because a PendingResult is returned you can get a notification when the write happens with the same kind of callback as before if desired.

Sign out and revoke

You may have noticed that GoogleApiClient doesn’t have a methods for clearDefaultAccount, getAccountName, or revokeAccessAndDisconnect. These options from PlusClient are part of the Plus.AccountApi. The value of the consistent approach to responses really shows with something like revoking access - instead of a custom callback type to get a signal once the user is disconnected, it will return a PendingResult which you can await or setResultCallback on just as with any other API.

Using the client with multiple APIs

Part of the original motivation for this change was to make it possible to add other APIs into a single GoogleApiClient connection. There was an example of connecting both Plus and Drive in one call by adding both APIs in the post on the Android developers blog. All that is required is multiple addApi and addScope calls for the various scopes and services required.

That’s about it! As more APIs find their way into Google Play services this type of client should make life a lot easier, and much simpler to extend as you want to add more functionality to your integration. If you have any questions on moving over try the Google+ developers community, or Stack Overflow tag.