Saturday, April 28, 2012

OAuth For Google API in Android


Auth is the preferred method for getting authorized access to a user's Google data. OAuth is an open standard for authorizing the use of data on the web. we can use OAuth for authorization with the Calendar service, other Google services, or with services from other companies that have adopted the standard.
To use OAuth, application must obtain an access token by following this sequence of token requests:
Client Login Method :
Client Login is one of the best method for obtaining Authentication token.With ClientLogin,application prompts the user for username and password on first run. After that, application uses a token for authorized access to the user's data.
To authenticate the user, send a POST request to the following URL: * https://www.google.com/accounts/ClientLogin*
Include the relevant parameters in the body of the POST request
Parameter For Client Login :
·      accountType:Type of account to request authorization for. Possible values are:
1      GOOGLE (get authorization for a Google account only)
2      HOSTED (get authorization for a hosted account only)
3      HOSTED_OR_GOOGLE (get authorization first for a hosted account; if attempt fails, get authorization for a Google account)
·      Email : User's full email address. It must include the domain (i.e.ramesh.turi@indianic.com).
·      Passwd :User's password.
·      service :Name of the Google service you're requesting authorization for.eg. The service name for Calendar is cl.
·      source = Short string identifying your application, for logging purposes. This string should take the form:
"companyName-applicationName-versionID". eg "indianic.projectname-1.0"
The POST request should be structured as a form post with the default encoding "application/x-www-form-urlencoded" because gogle api does not support any plaintext
so please in post request header set "Content-type" to "application/x-www-form-urlencoded".
If the request succeeds, then the response contains an alphanumeric string labeled Auth.
After a successful authentication request, use the Auth value to create an Authorization header for each request: * Authorization: GoogleLogin auth=yourAuthValue*
Function for getting Auth value :
public String getAuthentication(String email, String password) {
        String AUTH = "";
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(
                "https://www.google.com/accounts/ClientLogin");
        try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
            nameValuePairs.add(new BasicNameValuePair("Email", email)); 
            nameValuePairs.add(new BasicNameValuePair("Passwd", password)); 
            nameValuePairs.add(new BasicNameValuePair("accountType", "GOOGLE"));
            nameValuePairs.add(new BasicNameValuePair("source",
                    "Google-cURL-Example"));
            /**
             * for calendar service value is "cl"
             */
            nameValuePairs.add(new BasicNameValuePair("service", "cl")); 
            /***
             * // content-type must be "application/x-www-form-urlencoded"
             */
            post.setHeader("Content-type", "application/x-www-form-urlencoded");
            post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = client.execute(post);
            BufferedReader rd = new BufferedReader(new InputStreamReader(
                    response.getEntity().getContent()));
            String line = "";
            while ((line = rd.readLine()) != null) {
                Log.e("rd", line);
                if (line.startsWith("Auth=")) {
                    String s = line.substring(5);
                    AUTH = s;
                }
            }
            System.out.println(AUTH + "<-----------------");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return AUTH;
    }

this function returns the Auth value from the given user.
After getting Auth value, we can access google api which is mentioned in service parameter of client login request. eg "cl" for calendar so we can access any calendar api using this auth value.
to access any service use following code :
/// URL  = "https://www.google.com/calendar/feeds/default/owncalendars/full";
/// this url is used to getting the calendar list for user
 /// Authvalue = Authentication value   

public String getData(String URL, String Authvalue) {
        final DefaultHttpClient httpClient = createHttpClient();
        final HttpGet httpget = new HttpGet(URL);
        HttpResponse response = null;
        try {
            Log.i("Util", "posted Url:" + URL);
            httpget.setHeader("Authorization", "GoogleLogin auth=" + Authvalue);
            httpget.setHeader(HTTP.CONTENT_TYPE, "application/json");
            response = httpClient.execute(httpget);
            return EntityUtils.toString(response.getEntity());
        } catch (Exception e) {
            return "";
        }
    }
to get all response in json please append "alt=jsonc" to each service url.
Please refer to this given link for more information.
Reference : http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html

No comments:

Post a Comment