How to use Google implementation of OAuth 2.0 protocol to Access its APIs, Google Latitude example

This blog is about using the Google implementation of OAuth 2.0 authentication protocol using Java in JSF environment. Google refers to this process as Web server flow authentication. We will use Google Latitude as an example.

In order to access Google API you to have an Application registered with Google API console. The registration gives you client_id, client_secret, and an API key. You also have to define at least one redirect_url.

Web server flow authentication is a two part process. Getting a code and requesting for an access_token in exchange for the code.

The Code

The process starts by requesting an authorization URL from Google Authorization server. This is accomplished by using the following snippet.

public String getCode() {

    final String scope = "https://www.googleapis.com/auth/latitude.current.best";
    final String redirect_url = "http://kahimyang.info/kauswagan/Latitude.xhtml";
    final String client_id = "YOUR_CLIENT_ID";

    authorizeUrl = new GoogleAuthorizationRequestUrl(client_id,
            redirect_url, scope).build();

    return authorizeUrl;

}

The JSF markup that calls the bean method shown above.

<h:outputLink value="#{myBean.code}">
     <h:outputText value="Latitude" />
</h:outputLink>

  • redirect_url should be defined in the redirect URL of your Applications' API Access settings at the Google API console.
  • client_id is your Application client_id also from Google API console.
  • scope for Google Latitude is well documented in this page.
  • authorizeUrl will yield a screen like below.

If not already logged in, the user is presented with a login page before the authorization page like the one shown below is shown to the user.

User action takes us to the redirect_url. A code parameter is added to the request of the redirect_url if the user clicked on "Allow access" (granted permission) to your Application or an error if the user clicked on "No thanks".

The Access Token

The following method is part of the backing bean of the redirect_url.

String location;
String accessToken;
AccessTokenResponse authResponse;

public String getLocation() {
     return location;
}

@PostConstruct
void init () {
    FacesContext context = FacesContext.getCurrentInstance();
    HttpServletRequest request = 
            (HttpServletRequest) context.getExternalContext().getRequest();        

    String error = request.getParameter("error");
    // do something about the error.

    final String authorizationCode = request.getParameter("code");


    final String redirect_url = "http://kahimyang.info/kauswagan/Latitude.xhtml";
    final String CLIENT_ID = "APP_CLIENT_ID";
    final String CLIENT_SECRET = "YOUR_APP_SECRET";

    HttpTransport transport = new NetHttpTransport();
    JsonFactory json_factory = new JacksonFactory();


    try {

        // Exchange for an access and refresh token
        GoogleAuthorizationCodeGrant authRequest = 
                new GoogleAuthorizationCodeGrant(transport,
                json_factory, CLIENT_ID, CLIENT_SECRET, 
                authorizationCode, redirect_url);

        authRequest.useBasicAuthorization = false;

        authResponse = authRequest.execute();
        accessToken = authResponse.accessToken;

        // At this point we already have an access Token

        GoogleAccessProtectedResource access = 
                new GoogleAccessProtectedResource(accessToken,
                transport, json_factory, CLIENT_ID, CLIENT_SECRET, 
                authResponse.refreshToken);
        HttpRequestFactory rf = transport.createRequestFactory(access);

        final String ep = "https://www.googleapis.com/latitude/v1/currentLocation";

        GenericUrl gurl = new GenericUrl(ep);

        HttpRequest lreq = rf.buildGetRequest(gurl);
        lreq.setEnableGZipContent(false);

        HttpResponse lresp = lreq.execute();
        BufferedReader instream = 
                new BufferedReader(new InputStreamReader(lresp.getContent()));

        StringBuilder respData = new StringBuilder();

        String line;
        while ((line = instream.readLine()) != null) {
            respData.append(line);
        }

        Map<String, Map<String, Object>> gsonData = new LinkedHashMap();
        com.google.gson.Gson gs = new com.google.gson.Gson();
        gsonData = gs.fromJson(respData.toString(), gsonData.getClass());
        Map<String, Object> data = (Map<String, Object>) gsonData.get("data");
        String kind = (String) data.get("kind");
        if (kind.contains("latitude")) {
            Double lat = (Double) data.get("latitude");
            Double longi = (Double) data.get("longitude");
            //String timestamp = (String)data.get("timestamp");
            location = lat.toString() + "," + longi.toString();
        }
        

    } catch (Exception e) {
        // Log error
        location = "not found";
    }
}

Line 50 highlighted above is the end point URL which varies depending on the requested SCOPE. Please see the link that follows for more on latitude scopes. See downloads and documentation here.

google-api-java-client is used this this blog.

That's it. Good luck.


If you like the article, please share.
(Site URL pattern has changed as a result social actions counter was reset.)



Comment icon Comments (Newest first)