Integrating Google plus in grails application
In my current project, i needed to integrate Google+ in the application using server-side API. Google uses OAuth2.0 protocol for authorization when our application tries to access the data. All we require is an access token to fetch data from Google using REST calls which serves data in JSON format.
I implemented it using Web Server Applications API and thought it worth sharing.
There are basically 3 steps to fetch data from Google.
1. Register an application.
We need to register an application at Google API Console. Go to the Google console page using the link provided and create an aplication.
Steps involve in registering an application are:-
a.) Create project by providing name to the project.
b.) Turn ON the service required, in our case it is Google Plus API.
c.) Create a Oauth 2.0 Client ID.
d.) Create the OAuth 2.0 ClientId and provide the callback URL where google will send the authorization token.
e.) Note down Client ID and Client Secret as generated in the above step.
2. Obtain an Access Token from the Google Authorization Server.
Obtaining an access token involves 2 steps.
a.) Request for Authorization Code.
In this step, we will request the Google server for authorization code by providing registered application client ID in the URL to Google server.
I created an action to redirect to Goolge, when someone want to connect to google plus.
[java]
String CLIENT_ID =client_id_obtained from registered app
String CALLBACK_URL = callback_url_as_mentioned in the registered app.
String GOOGLE_PLUS_SCOPE=’https://www.googleapis.com/auth/plus.me’ // scope is the permissions we are requesting.
[/java]
Action code is as:
[java]
def registerOnGooglePlus = {
String authorizeUrl = "https://accounts.google.com/o/oauth2/auth?scope=${GOOGLE_PLUS_SCOPE}&
redirect_uri=${CALLBACK_URL}&response_type=code&client_id=${CLIENT_ID}&access_type=offline"
URL urlForGooglePlus = new URL(authorizeUrl)
redirect(url: urlForGooglePlus)
}
[/java]
The Redirect will take user to permissions page, if the user is already logged-in or will take to login page and then permissions page.
After approving the required permissions, user will redirect back to the application’s registered Callback URL with the authorization code.
b.) Request for Access Token with the authorization code obtained from the above action.
Access Token can be received by a POST request using the Client Secret and authorization code received.
The POST call requires 5 properties to be send in the body of the request in the encoded form.
[html]
code : The authorization code returned from the initial request
client_id : The client_id obtained during application registration
client_secret : The client secret obtained during application registration
redirect_uri : The URI registered with the application
grant_type : authorization_code
[/html]
[java]
// Sample action to receive authorization code
def callBack={
StringBuilder sb = new StringBuilder("code=");
sb.append(URLEncoder.encode(code, "UTF-8"));
sb.append("&client_id=");
sb.append(URLEncoder.encode(clientId, "UTF-8"));
sb.append("&client_secret=");
sb.append(URLEncoder.encode(clientSecret, "UTF-8"));
sb.append("&redirect_uri=");
sb.append(URLEncoder.encode(callbackUrl, "UTF-8"));
sb.append("&grant_type=");
sb.append(URLEncoder.encode(‘authorization_code’, "UTF-8"));
String URL_TO_REQUEST_TOKEN= ‘https://accounts.google.com/o/oauth2/token’
URL url = new URL(URL_TO_REQUEST_TOKEN);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
try {
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" + sb.toString().length());
connection.setRequestProperty("Host", "accounts.google.com");
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(connection.getOutputStream());
outputStreamWriter.write(sb.toString());
outputStreamWriter.flush();
log.debug("Response code ${connection.responseCode} , Message : ${connection.responseMessage}")
String resultData = connection.content.text
def responseJson = JSON.parse(resultData)
String ACCESS_TOKEN = responseJson?.access_token
}
catch (Exception e) {
e.printStackTrace()
}
}
[/java]
3. Calling Google API.
Now, with the help of access token, we can call google API to fetch Data by appending the access token in the GET request.
Example:
To fetch person’s profile data
[java]
GET : https://www.googleapis.com/oauth2/v1/userinfo?access_token=ACCESS_TOKEN
[/java]
To get list of profile acitivties
[java]
GET :
[/java]
References:-
http://code.google.com/apis/accounts/docs/OAuth2WebServer.html
http://code.google.com/apis/accounts/docs/OAuth2.html
Hope this helps..!!!
Vishal Sahu
vishal[at]intelligrape[dot]com
that is great thanks for share us.please continue
Thank you Boss. Great Tutorial.
great example..
had to set doOutput to true for it to work for the oauthToken retrieval
Please, nevermind about my last question. I make it works! It was my IDE fault, it doesn’t recognize some commands but it still there.
Now I will try to retrieve google information about name, age, etc.
Thanks!
Thanks Vishal for the great example, but I have some questions to do.
I’ve tried to reproduce the same code of you, but I noticed some difference incoming. First I had to put “setDoOutput(true)” to “connection” and I can’t access “connection.content.text” because it doesn’t exist there. Maybe because the grails version (mine is 2.0.1) I really don’t know. So I guess I’m sending the post response but I can’t handle it’s returning.
Thanks!
How to log out
Hi Martin,
Yes we can store the token for future use, it comes with an expiry date, before that it equally valid.
We can also refresh that access token(when it expires) with the help of refresh token obtained along with the access token.
http://code.google.com/apis/accounts/docs/OAuth2WebServer.html
Excellent blog, exactly what I was looking for. Can you store the ACCESS_TOKEN for future use? Kinda like when you use AuthSub… How long does the ACCESS_TOKEN last?