My favorites | English | Sign in

Google Friend Connect APIs (Labs)

Server-side Integration of GFC

In addition to letting you run social gadgets on your website and display social information using JavaScript, Friend Connect can also be integrated with existing server-side code. One type of integration possible is with an existing login system, letting anyone with a Friend Connect account log into your website without having to complete a registration process.

Writing a step-by-step guide to cover every login system is impossible, so this article takes a conceptual approach and does not give much in the way of copy-and-paste code samples. You will need to be familiar with the login system of your web application platform, and with the way that it processes requests and responses.

By implementing the approach described in this article, you will open up your site to a large pool of potential users who simply have to click a button to log into your site. Additionally, you will be given information about the relationships between users of your website, allowing you to provide a rich and engaging social experience.

Contents

  1. Overview - Using Friend Connect as an identity provider
  2. Letting users sign in
    1. Install the inline JavaScript code
    2. Give users an option of logging in with Friend Connect
  3. Fetching social data from your server
    1. Using a site authentication cookie
    2. Redirecting after a user signs into Friend Connect on your site.
    3. Using two-legged OAuth
    4. Making server-to-server requests
  4. Friend Connect controls for logged in users
    1. Settings
    2. Invite
    3. User profiles
    4. Letting users sign out
  5. Design considerations
    1. Integrating with an existing login system
    2. Adding social features to your website
  6. For more information

Overview - Using Friend Connect as an identity provider

The process of allowing Friend Connect users to log into your website will be slightly different on each site, depending on the existing login system that is currently in use. Thankfully, most integrations will follow the same general process:

  1. Give users the ability to sign into Friend Connect, using the standard JavaScript API.
    You can achieve this in only a few lines of JavaScript code.

  2. Pass Friend Connect authentication credentials to your server.
    By passing a security token to your server, you can use the OpenSocial client libraries to make server-to-server calls on behalf of the current user.

  3. Change your data model and authorization code to accept Friend Connect logins.
    Your login code needs to be able to check for a logged-in Friend Connect user and integrate that data with the existing accounts on your website. You'll need to extend your data model to keep track of a Friend Connect ID per account, and pull profile fields from the server-to-server APIs.

  4. Display additional controls for logged-in Friend Connect users.
    Your Friend Connect users will need additional controls to manage their settings. Thankfully, this is possible with a small bit of JavaScript.

  5. Log a user out of Friend Connect when they sign out of your site.
    Logging out of Friend Connect can only be done through JavaScript. You may need to restructure your logout page for Friend Connect users.

  6. Determine how to present your site's data in a social way.
    The web is better when it is social! If you run a review site, show users reviews that their friends have recently posted. If you have an online game, let friends compare high scores. Use your imagination!

Letting users sign in

Even though you will be working with Friend Connect data server-side, logging into Friend Connect still requires use of the JavaScript API.

Install the inline JavaScript code

You will need to add the Friend Connect JavaScript code to your login page. Follow the instructions listed in the JavaScript API reference and your login page should contain code similar to this:

<script src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
  google.load('friendconnect', '0.8');
</script>
<script type="text/javascript">    
  google.friendconnect.container.loadOpenSocialApi({
    site: 'XXXXXXXXXXXXXXXXXXXX',
    onload: function(securityToken) {}
  });
</script>

Note the line that looks like onload: function(securityToken) {}. This is where you specify an onload handler which will be called when the OpenSocial API finishes loading. If you have JavaScript code that requires the OpenSocial APIs to be loaded before running, put that code here.

Once the Friend Connect JavaScript is correctly installed in your page, you'll need to offer users a means to log in.

Give users an option of logging in with Friend Connect

Users of your site need a way to sign into Friend Connect, but since they won't be sharing their Friend Connect password with your site, the interface will be a little different from a standard login username and password form. Create a link that will open a new window to the Friend Connect authentication page by using the following code:

<a href="#" onclick="google.friendconnect.requestSignIn();">Sign in</a>

Friend Connect can also dynamically generate a login button for you to use. To render a button that looks like example of a sign in button, simply execute the following code:

google.friendconnect.renderSignInButton({ 'id': 'target-id', 'text' : 'Click here to join ', 'style': 'standard' });

This site has more information about the renderSignInButton method, including examples of the different styles you may use.

Friend Connect lowers the barrier to entry for new users to interact with your site. Make sure to structure your login UI to show users that Friend Connect can be used as an alternative to registering a new account.

Shows a website with two login options.

Once the google.friendconnect.requestSignIn() function is executed, or a Friend Connect button is clicked, a pop-up window will appear and the user will be prompted to sign in to your site. The contents of the window are generated by Friend Connect, so you don't have to worry about customizing another user interface or handling a complicated authorization process.

Fetching social data from your server

Once a user has joined your site, their information will be available to your through Friend Connect's server-to-server APIs. These APIs are implementations of OpenSocial's REST and RPC Protocols, so you will be able to use the OpenSocial client libraries to fetch information about the Friend Connect users who have joined your site.

Use of the REST and RPC Protocols will be slightly different depending on context. If a user is currently interacting with your site and you wish to make Friend Connect calls on behalf of them, you will use a site authentication cookie to make social API calls. For times where you want to access social data about your site members when there is no user interacting with your site (to do background processing, for example) you will use a method called two-legged OAuth to make your calls. For a full listing of the authentication options available to your website, please view the REST and RPC protocol page.

Using a site authentication cookie

Whenever a user signs into a Friend Connect enabled site, a cookie is placed on the domain of the site. The cookie has the name "fcauth" + <your siteId> and its value can be used to authorize calls to Friend Connect's REST and RPC APIs. Simply attach it as a querystring parameter named fcauth to every request you make to the Friend Connect APIs.

For example, the following URL will fetch the viewer's data via REST :

http://www.google.com/friendconnect/api/people/@viewer/@self?fcauth=<cookie value>

Keep the following in mind:

  • API calls will be made using the identity of the user who passed you the cookie in a request.
  • The cookie is long-lived, but does expire after some number of months.

This authorization method is exclusive to Friend Connect, but is supported by the following OpenSocial client libraries. The supplied links point to wiki pages with language-specific instructions on how to use the fcauth parameter:

Redirecting after a user signs into Friend Connect on your site.

If a signed in user visits any page on your site, their browser will send the fcauth cookie to your server, but if the user signs into Friend Connect while visiting your sign-in page, you will need to redirect the browser in order to pass the cookie to your server. This will have to be done via JavaScript because Friend Connect will not refresh the page after the user signs in.

Here is one way you can authenticate users using the fcauth cookie. Assume your site has the pages login.html and authenticate.html

  1. On login.html, insert the sign in button code.
  2. After the user signs into Friend Connect on login.html, you must redirect them to authenticate.html. Since the onload handler you specified for the google.friendconnect.container.loadOpenSocialApi call will be executed once when the page loads and again when the user signs in, write code to redirect the browser the second time the function is called:
    google.friendconnect.container.loadOpenSocialApi({
      site: 'XXXXXXXXXXXXXXXXXXXX',
      onload: function() {
        if (!window.timesloaded) {
          window.timesloaded = 1;
        } else {
          window.timesloaded++;
        }
        if (window.timesloaded > 1) {
          window.top.location.href = "/authenticate.html";
        }
      }
    });
    
  3. On your server, write code to check for the fcauth cookie upon requests to authenticate.html. If a valid cookie is found, this value should be used to obtain the viewer and establish a signed in session. if the cookie is not found or does not return a valid viewer, redirect the user back to login.html.

Using two-legged OAuth

Two-legged OAuth is an authorization method which allows your site to make calls to the Friend Connect APIs without a user's security token, perfect for background processing or fetching data which may have expired from your server's cache.

To get your keys, visit the "For developers" portion of the Friend Connect admin site. You will see sections labeled "2 Legged OAuth Shared Consumer Secret" and "2 Legged OAuth Consumer Key" containing the shared secret and consumer key, respectively.

The following OpenSocial client libraries support 2-legged OAuth:

Making server-to-server requests

Regardless of the method you use to authorize your requests, Friend Connect uses the OpenSocial REST and RPC Protocols, so there are several OpenSocial client libraries you may use to access Friend Connect data.

You will be able to make requests to:

  • Fetch profile information about the users of your site.
  • Fetch the list of friends of a given user.
  • Post and retrieve activities for the users of your site.
  • Set and retrieve small amounts of persistent application data for each user.

Please see the REST and RPC Protocol specifications for more information about making server-to-server requests.

Friend Connect controls for logged in users

Now that you are able to let Friend Connect users log in, you should add a few features that will help them use your site.

First, you can generate two utility links that will create pop-up windows when clicked. Determine whether the logged in user is a Friend Connect user and if so, render the following two links:

Settings

Settings pop-up dialog.

The settings window will allow the user to configure their Friend Connect accounts, manage their friends, and unjoin your site if needed. To generate this pop-up, call google.friendconnect.requestSettings() from a click event handler:

<a href="#" onclick="google.friendconnect.requestSettings();">Settings</a>

Invite

Invite pop-up dialog.

The invite window will allow a Friend Connect user to ask their friends to join your website. This pop-up is opened by calling google.friendconnect.requestInvite() from a click event handler:

<a href="#" onclick="google.friendconnect.requestInvite();">Invite</a>

User profiles

If you fetch the profileUrl field from a Friend Connect user, you'll notice that the link is to your site's Home URL. The additional query parameters cause the user's profile to be displayed in a Lightbox.

Letting users sign out

The only way to sign a user out of Friend Connect is through the google.friendconnect.requestSignOut() JavaScript call, which can be problematic if you need to do server-side processing upon a user logging out (ending a session, for example). If you need to perform an server-side action upon logout, create a page for logging out on your site (logout.html, for example) and use the following code to log out the current user:

google.friendconnect.container.loadOpenSocialApi({
  site: 'XXXXXXXXXXXXXXXXXXXX',
  onload: function(securityToken) {
    if (!window.timesloaded) {
      window.timesloaded = 1;
      google.friendconnect.requestSignOut();
    } else {
      window.timesloaded++;
    }
    if (window.timesloaded > 1) {
      window.top.location.href = "/login.html";
    }
  }
});

When the page first loads, it will trigger the onload handler, which calls google.friendconnect.requestSignOut() and requests that the current user be signed out. When this call is complete, it will trigger the onload handler again, at which point the page will redirect to login.html. On the server side, you can perform whatever session cleanup you need to do when logout.html is called, and in your site UI, just generate all of your sign out links like this:

<a href="logout.html" >Sign out</a>

If you don't need to clean up upon sign out, just generate the sign out links for Friend Connect users like this (keeping in mind that if you use more than one login system, you'll have to generate different links for your other users):

<a href="#" onclick="google.friendconnect.requestSignOut();">Sign out</a>

Design considerations

By now you should have a general view of how several components of Friend Connect can be put together to form a login system for a website, but you will likely have many design challenges when performing the integration yourself. This section will cover some higher level concepts that you should keep in mind when applying Friend Connect to your site.

Integrating with an existing login system

One of the most difficult parts of adding Friend Connect users to your site will be changing your login system to accept a friend connect user as "just another" registered user on your site. Here are some tips to help you plan your integration:

  • Extend your data model to support Friend Connect users.
    If you're using a relational database and have a table named "Accounts", add an optional column for the Friend Connect ID number. This way, if a registered user also logs in with Friend Connect, you can combine their accounts together. If you're using an object-oriented database, see if you can extend your standard Account model with a FriendConnectAccount subclass with the extra field.

  • Accounts should not persist Friend Connect data.
    When you load an Account, check to see whether there's a Friend Connect ID attached and use the OpenSocial client library to populate the account with the appropriate data. Since you don't want to fetch a user over the network every time you pull from your database, employ a caching system, like memcached or APC.

  • Write a wrapping layer.
    Write a layer between the OpenSocial client library and your web application that will handle mapping OpenSocial Person data to your site's Accounts. Every time you get a Person record from the OpenSocial client, fetch the associated Account and pass that to the rest of your application. If you're unable to find an associated Account, treat that Person like a newly registered user to your site and run any appropriate initialization methods.

  • Build a user provider infrastructure.
    You'll need an abstract way of dealing with accounts on your site, no matter if they come from Friend Connect or your local registration. Write a class called AccountProvider that has the following methods:

    authorize(request) (static method) Looks at the request and attempts to get a username and password. If valid credentials are found, this sets the corresponding Account to the session as the viewer and returns an AccountProvider instance. Otherwise, this returns null
    get_viewer() Gets the logged-in Account from the session.
    get_viewer_friends() Return null.
    get_account_by_id(id) Returns the specified Account. If the Account has a Friend Connect ID associated with it, use two-legged OAuth to request the profile data.

    Now write a class named FriendConnectProvider which inherits from AccountProvider. This should override:

    authorize(request) (static method) Looks at the request and attempts to get the site cookie, which it uses to request the viewer. If a valid viewer is found, this method sets the corresponding Account to the session as the viewer, stores the cookie in the session for later use, and returns a FriendConnectProvider instance. Otherwise, this returns null
    get_viewer_friends() Use the stored site cookie to request the viewer's friends from Friend Connect.

    Now when you authorize the user (say, in your authorization page), you can follow the approach listed in the following pseudocode:

    session.provider = AccountProvider.from_request(request) or
                       FriendConnectProvider.from_request(request);
    if (!session.provider) {
      redirect("/login.html");
    } else {
      redirect("/home.html");
    }
    

    Now, no matter what kind of user is logged in, you can call session.provider.get_viewer() and session.provider.get_viewer_friends() (although only the Friend Connect users will actually ever get a list of friends).

Adding social features to your website

When you add Friend Connect as a user provider, you get a friendship model for free. Think about ways that your website could be made more social:

  • When a user adds content to your site, would their friends be interested in it?
  • Can you use the activity stream API to show an interesting view of what a user's friends have been doing on your site?
  • Can you create a "friends' high scores" table and get users to compete against each other?

For more information

By now, you should have an understanding of the core concepts needed to deeply integrate Friend Connect into your website. For a working example of such an integration, check out the following resources:

  • The Chow Down - A running website that integrates an existing login system with Google Friend Connect.
  • Server integration article - Walks you through the source code of The Chow Down, to show how the integration was accomplished.
  • The complete source code of The Chow Down will be made available shortly.