Purpose: This doc provides java code for OAuth 2.0 functions offered by the Google OAuth Client Library for Java.
To start using Google APIs for google Auth, a project needs to be setup on the Google API Console for auth, Your application can be a mobile application or web server etc.
Reference Documentation:- https://support.google.com/cloud/answer/6158849?hl=en&ref_topic=6262490
You will get Client id and client secret key after following above steps in google developer console.
"/loginGoogleAuth" method will return the google redirect uri.
@RequestMapping(value = "/loginGoogleAuth", method = { RequestMethod.POST, RequestMethod.GET })
public String loginGoogleAuth(ModelMap model, HttpServletRequest request, HttpServletResponse response) {
return "redirect:" + googleOAuth2LoginService.getOAuthURL();
}
"/googleOAuth2callback" will be called if authentication is successful with google. In Response call, we get auth code, that will be used to get the auth token from goggle using auth api. Then using this auth token, We can fetch basic user details from google.
@RequestMapping(value = "/googleOAuth2callback", method = { RequestMethod.POST, RequestMethod.GET })
public String googleOAuth2callback(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws IOException {
String errorCode = request.getParameter("error");
if (errorCode != null) {
LOG.info("failure in login");
return "login";
}
String returnUrl = request.getParameter(RETURN_URL);
String authCode = request.getParameter(AUTH_CODE);
try {
GoogleUserDetails user = oauthService.authenticateWithGoogleOverOAuth2(authCode);
// create a user if required. Initiate the session for this user.
} catch (Throwable t) {
LOG.info("failure in login", t);
return "login";
}
}
To start using Google APIs for google Auth, a project needs to be setup on the Google API Console for auth, Your application can be a mobile application or web server etc.
Reference Documentation:- https://support.google.com/cloud/answer/6158849?hl=en&ref_topic=6262490
You will get Client id and client secret key after following above steps in google developer console.
Google OAuth authorization code flow for Java
Jsp Page:- This page will call the controller to get the redirect URL for google, where user will get authenticated and return to Succes redirect url provided by our application.
<form:form id="formAuth" action="loginGoogleAuth" name="loginGoogleAuth" >
<p><strong>Proceed for Authentication via Google</strong></p>
<br/><div> <button type="submit" id="submitButton">Sign In</button></div>
</div>
</form:form>
<p><strong>Proceed for Authentication via Google</strong></p>
<br/><div> <button type="submit" id="submitButton">Sign In</button></div>
</div>
</form:form>
Contoller:- Google
API does not return user info directly into response on successful
redirection. So we need to call 2 apis, one to get authtoken using auth code and Second using authtoken user details can be fetched.
"/loginGoogleAuth" method will return the google redirect uri.
@RequestMapping(value = "/loginGoogleAuth", method = { RequestMethod.POST, RequestMethod.GET })
public String loginGoogleAuth(ModelMap model, HttpServletRequest request, HttpServletResponse response) {
return "redirect:" + googleOAuth2LoginService.getOAuthURL();
}
"/googleOAuth2callback" will be called if authentication is successful with google. In Response call, we get auth code, that will be used to get the auth token from goggle using auth api. Then using this auth token, We can fetch basic user details from google.
@RequestMapping(value = "/googleOAuth2callback", method = { RequestMethod.POST, RequestMethod.GET })
public String googleOAuth2callback(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws IOException {
String errorCode = request.getParameter("error");
if (errorCode != null) {
LOG.info("failure in login");
return "login";
}
String returnUrl = request.getParameter(RETURN_URL);
String authCode = request.getParameter(AUTH_CODE);
try {
GoogleUserDetails user = oauthService.authenticateWithGoogleOverOAuth2(authCode);
// create a user if required. Initiate the session for this user.
} catch (Throwable t) {
LOG.info("failure in login", t);
return "login";
}
}
Service:-
public class GoogleOAuth2Service {
private static final Logger LOG = LoggerFactory.getLogger(GoogleOAuth2Service.class);
private String userInfoUrl="https://www.googleapis.com/oauth2/v2/userinfo";
private String authUrl="https://accounts.google.com/o/oauth2/v2/auth";
private String tokenUrl="https://www.googleapis.com/oauth2/v4/token";
private String redirectUri="http://googleoauthdemo.com/googleOAuth2callback";
private String clientId="Client_Id";
private String clientSecret="Client_Secret_Key";
public String getOAuthURL() {
StringBuilder oauthUrl = new StringBuilder().append(authUrl).append("?client_id=").append(clientId)
.append("&response_type=code")
.append("&scope=openid%20email+https://www.googleapis.com/auth/userinfo.profile")
.append("&redirect_uri=" + redirectUri);
return oauthUrl.toString();
}
public GoogleUserDetails authenticateWithGoogleOverOAuth2(String authCode) throws IOException {
String accessToken = getOAuthToken(authCode);
GoogleUserDetails googleUserDetails = ERRORgetUserDetailsAccessToken(accessToken);
return googleUserDetails;
}
public String getOAuthToken(String code) throws IOException {
ImmutableMap<String, String> requestParameters = ImmutableMap.<String, String> builder().put("code", code)
.put("client_id", clientId).put("client_secret", clientSecret).put("redirect_uri", redirectUri)
.put("grant_type", "authorization_code").build();
String body = _sendPostRequest(tokenUrl, requestParameters);
Map<String, String> postResponse = jsonConverter.convertJsonToMap(body);
return postResponse.get("access_token");
}
public GoogleUserDetails getUserDetailsAccessToken(String accessToken) throws IOException {
LOG.trace("Fetching User Details from Google using access Token: {}", accessToken);
String userDetailsAsJson = _sendGetRequest(
new StringBuilder(userInfoUrl).append("?access_token=").append(accessToken).toString());
LOG.debug("user info {}", userDetailsAsJson);
Map<String, String> userDetailsAsMap = jsonConverter.convertJsonToMap(userDetailsAsJson);
return GoogleUserDetails.buildFromMap(userDetailsAsMap);
}
private String _sendGetRequest(String url) throws ClientProtocolException, IOException {
return _sendHttpRequest(new HttpGet(url));
}
private String _sendPostRequest(String url, Map<String, String> formParameters)
throws ClientProtocolException, IOException {
HttpPost request = new HttpPost(url);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (String key : formParameters.keySet()) {
nvps.add(new BasicNameValuePair(key, formParameters.get(key)));
}
request.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
return _sendHttpRequest(request);
}
private String _sendHttpRequest(HttpRequestBase request) throws ClientProtocolException, IOException {
LOG.info("Sending Request to Google");
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
String body = EntityUtils.toString(entity);
LOG.info("Response body>>" + body);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException(
"Expected 200 but got " + response.getStatusLine().getStatusCode() + ", with body " + body);
}
return body;
}
}
public class GoogleOAuth2Service {
private static final Logger LOG = LoggerFactory.getLogger(GoogleOAuth2Service.class);
private String userInfoUrl="https://www.googleapis.com/oauth2/v2/userinfo";
private String authUrl="https://accounts.google.com/o/oauth2/v2/auth";
private String tokenUrl="https://www.googleapis.com/oauth2/v4/token";
private String redirectUri="http://googleoauthdemo.com/googleOAuth2callback";
private String clientId="Client_Id";
private String clientSecret="Client_Secret_Key";
public String getOAuthURL() {
StringBuilder oauthUrl = new StringBuilder().append(authUrl).append("?client_id=").append(clientId)
.append("&response_type=code")
.append("&scope=openid%20email+https://www.googleapis.com/auth/userinfo.profile")
.append("&redirect_uri=" + redirectUri);
return oauthUrl.toString();
}
public GoogleUserDetails authenticateWithGoogleOverOAuth2(String authCode) throws IOException {
String accessToken = getOAuthToken(authCode);
GoogleUserDetails googleUserDetails = ERRORgetUserDetailsAccessToken(accessToken);
return googleUserDetails;
}
public String getOAuthToken(String code) throws IOException {
ImmutableMap<String, String> requestParameters = ImmutableMap.<String, String> builder().put("code", code)
.put("client_id", clientId).put("client_secret", clientSecret).put("redirect_uri", redirectUri)
.put("grant_type", "authorization_code").build();
String body = _sendPostRequest(tokenUrl, requestParameters);
Map<String, String> postResponse = jsonConverter.convertJsonToMap(body);
return postResponse.get("access_token");
}
public GoogleUserDetails getUserDetailsAccessToken(String accessToken) throws IOException {
LOG.trace("Fetching User Details from Google using access Token: {}", accessToken);
String userDetailsAsJson = _sendGetRequest(
new StringBuilder(userInfoUrl).append("?access_token=").append(accessToken).toString());
LOG.debug("user info {}", userDetailsAsJson);
Map<String, String> userDetailsAsMap = jsonConverter.convertJsonToMap(userDetailsAsJson);
return GoogleUserDetails.buildFromMap(userDetailsAsMap);
}
private String _sendGetRequest(String url) throws ClientProtocolException, IOException {
return _sendHttpRequest(new HttpGet(url));
}
private String _sendPostRequest(String url, Map<String, String> formParameters)
throws ClientProtocolException, IOException {
HttpPost request = new HttpPost(url);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (String key : formParameters.keySet()) {
nvps.add(new BasicNameValuePair(key, formParameters.get(key)));
}
request.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
return _sendHttpRequest(request);
}
private String _sendHttpRequest(HttpRequestBase request) throws ClientProtocolException, IOException {
LOG.info("Sending Request to Google");
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
String body = EntityUtils.toString(entity);
LOG.info("Response body>>" + body);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException(
"Expected 200 but got " + response.getStatusLine().getStatusCode() + ", with body " + body);
}
return body;
}
}
public class GoogleUserDetails {
public static final String PROP_FAMILY_NAME = "family_name";
public static final String PROP_GIVEN_NAME = "given_name";
public static final String PROP_EMAIL = "email";
private String email;
private String firstName;
private String lastName;
private GoogleUserDetails() {
}
public static GoogleUserDetails buildFromMap(Map<String, String> userDetails) {
GoogleUserDetails gud = new GoogleUserDetails();
gud.setEmail(userDetails.get(PROP_EMAIL));
gud.setFirstName(userDetails.get(PROP_GIVEN_NAME));
gud.setLastName(userDetails.get(PROP_FAMILY_NAME));
return gud;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
public static final String PROP_FAMILY_NAME = "family_name";
public static final String PROP_GIVEN_NAME = "given_name";
public static final String PROP_EMAIL = "email";
private String email;
private String firstName;
private String lastName;
private GoogleUserDetails() {
}
public static GoogleUserDetails buildFromMap(Map<String, String> userDetails) {
GoogleUserDetails gud = new GoogleUserDetails();
gud.setEmail(userDetails.get(PROP_EMAIL));
gud.setFirstName(userDetails.get(PROP_GIVEN_NAME));
gud.setLastName(userDetails.get(PROP_FAMILY_NAME));
return gud;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
No comments:
Post a Comment