Thursday, May 24, 2012

How to use Google Login for your App

You need to register your app on Google first to get identified by it.
Register here !

Steps to Register Your App.

1. Click on "Create Project"
2. It takes you to the Services Tab. Skip that step ans instead select the "API Access" Tab.
3. Click on "Create an OAuth 2.0 client ID"
4. Fill in the pop-up form with the info associated with your app, like your App name (Product Name), email id to which you want to associate this app, and the app logo url. Click Next.
5. Select the App type, give your site url. For development phase, you are allowed to give the site url as http://localhost:8080/ (or any other relevant port) as well.
6. If you click on more options link, you can enter the redirect url also for your app. The JavaScript origin becomes your site url.
7. Click on "Create Client ID"

Your App is registered now!

Google generates an App ID, or the Client ID for your app. It also generates a App Secret which should not be disclosed and an email address for the app.

In the log-in page of your application, open the following request url (either by button-click, href, ajax, get request, or window.open)

"https://accounts.google.com/o/oauth2/auth?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&redirect_uri=http%3A%2F%2Fwww%2Eyourappdomain%2Ecom%2F&response_type=token&client_id=YOUR_APP_ID"
                               
You will be prompted by Google to permit the app to access your Google account. If you reject, Google will send you an error, else it will send you an access token along with the return url separated by a #. Since your scope was "email" in the above request url, you will get to know user's basic account details, like his username, email, first name, last name.

You must provide a redirect url for a file where you want to start a proper user session (as when the user is logged in). There you should check whether Google has provided you an access code or not in the return url.

Once you have received an access code it means you have permitted the app to use your Google account to access your basic details. Write the following code in your return url file.

Because the access token comes along with a # separator you need to extract it for the next request. Check the sample code below:

var params = {}, queryString = location.hash.substring(1),
    regex = /([^&=]+)=([^&]*)/g, m;
    while (m = regex.exec(queryString)) {
      params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
    }
    var queryStringArray = queryString.split("&");
    if(queryStringArray[0].split("=")[0] == "access_token"){
    // make a Get request to 'https://www.googleapis.com/oauth2/v1/userinfo?' + queryStringArray[0]
    // i used an ajax call to open the url from the servlet as follows:

    $.ajax({
                    type : 'GET',
                    url : '/servlet',
                    contentType: "text/xml; charset=utf-8",
                    dataType : 'xml',
                    data: {
                        action : 'googleLogin',
                        apiURL : 'https://www.googleapis.com/oauth2/v1/userinfo?' + queryStringArray[0]

                    },
                    success : function(xmlData){
                           
                    }
        });
    }else if(queryStringArray[0].split("=")[0] == "error"){
        alert("You haven't approve the app to access your account info");
        location = "your_login_page";
    }

    In your Servlet, handle the ajax action in a method as follows:

    public void getUserData() {

    URL url = new URL(request.getParameter("apiURL"));
    URLConnection conn = url.openConnection ();
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    StringBuffer sb = new StringBuffer();
    String line;
    while ((line = rd.readLine()) != null)
    {
        sb.append(line);
    }
    rd.close();
    String result = sb.toString();
    String userData = parseUserInfoOAuthResponse(result);
}

The "result" string will contain all the user profile information, like his first name , last name, email. You need to parse this data from the string.

It is obvious that Google will never allow you to access user's password, hence you will have to create a random password for the user account, which he can change anytime later.

No comments:

Post a Comment