oAuth 2.0 with google account with Java Spring MVC

Varun   Varun 585 Views
Integrating your web app with google using oAuth2.0 is really very simple, lets see an example using Java Sprint MVC, also works on google app engine....

following is the link to be created on your webpage which will be clicked by end user to connect using Google credentials,

<a target="_blank" href="https://accounts.google.com/o/oauth2/auth?response_type=code
&client_id=**************************************************.apps.googleusercontent.com&scope=profile email&redirect_uri=http://localhost:8888/googleOauth2callback">Google</a>

Following is the java controller code to connect:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class GoogleoAuth {

@RequestMapping(value="/googleOauth2callback", method = RequestMethod.GET)
public String googleOauth2callback(ModelMap model,HttpServletRequest req) {
HttpPostHelper hph = new HttpPostHelper();
try{
HashMap<String,String> parameters = new HashMap<String,String>();
parameters.put("code", req.getParameter("code"));
parameters.put("client_id", "***********************************.apps.googleusercontent.com");
parameters.put("client_secret", "**********************");
parameters.put("redirect_uri", "http://www.sampleSite.com/googleOauth2callback");
parameters.put("grant_type", "authorization_code");
String output= hph.sendHTTPsPost(
"https://www.googleapis.com/oauth2/v3/token", parameters);
model.put("response", output);
@SuppressWarnings("unchecked")
Map<String,Object> returnMap = (Map<String,Object>)JsonUtil.jsonStringToObject(output); 
// jsonStringToObject is method to convert json string into object, write your own, 
try{
model.put("response", returnMap.get("access_token"));
String outputProfile = hph.sendHTTPGet(
"https://www.googleapis.com/plus/v1/people/me?access_token="+returnMap.get("access_token"), 
null
);
returnMap = (Map<String,Object>)JsonUtil.jsonStringToObject(outputProfile);
Map<String,String> emailMap = ((ArrayList<LinkedHashMap<String,String>>)returnMap.get("emails")).get(0);
model.put("dEmail",emailMap.get("value"));
model.put("dName",returnMap.get("displayName"));
}catch(Exception e){
e.printStackTrace();
return "login";
}
}catch(Exception e){
e.printStackTrace();
return "login";
}
return "googleOauth2callback"; // jsp file name
}

 

}