I am working on Hybris Technology. It is nothing but the Java only. So I am trying to Integrate Google Login Button with my Java Application.
I am following this tutorial. Here is my code What I am doing
Front Part --
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
</script>
<script type="text/javascript">
(function () {
var po = document.createElement('script');
po.type = 'text/javascript';
po.async = true;
po.src = 'https://plus.google.com/js/client:plusone.js?onload=start';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(po, s);
})();
</script>
<div id="signinButton">
<span class="g-signin" data-scope="https://www.googleapis.com/auth/plus.login"
data-clientid="*****************************"
data-redirecturi="postmessage"
data-accesstype="offline"
data-cookiepolicy="single_host_origin"
data-callback="signInCallback">
</span>
</div>
<div id="result"></div>
<script type="text/javascript">
function signInCallback(authResult) {
if (authResult['code']) {
// Hide the sign-in button now that the user is authorized, for example:
$('#signinButton').attr('style', 'display: none');
// Send the code to the server
$.ajax({
type: 'GET',
url: '/store/en/login/lnregister',
contentType: 'application/octet-stream; charset=utf-8',
success: function(result) {
// Handle or verify the server response if necessary.
// Prints the list of people that the user has allowed the app to know
// to the console.
console.log(result);
if (result['profile'] && result['people']){
$('#results').html('Hello ' + result['profile']['displayName'] + '. You successfully made a server side call to people.get and people.list');
} else {
$('#results').html('Failed to make a server-side call. Check your configuration and console.');
}
},
processData: false,
data: authResult['code']
});
} else if (authResult['error']) {
// There was an error.
// Possible error codes:
// "access_denied" - User denied access to your app
// "immediate_failed" - Could not automatially log in the user
// console.log('There was an error: ' + authResult['error']);
}
}
</script>
Here I am using ajax to call my controller function lnregister
.
@RequestMapping(value = "/lnregister", method = RequestMethod.GET)
public String doLnRegister(@RequestHeader(value = "referer", required = false) final String referer, final RegisterForm form,
final BindingResult bindingResult, final Model model, final HttpServletRequest request,
final HttpServletResponse response, final RedirectAttributes redirectModel) throws CMSItemNotFoundException
{
final Gson gson = new Gson();
final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
final String APPLICATION_NAME = "HybrisProject";
final HttpTransport TRANSPORT = new HttpTransport()
{
@Override
protected final LowLevelHttpRequest buildRequest(final String arg0, final String arg1) throws IOException
{
// YTODO Auto-generated method stub
return null;
}
};
final String CLIENT_ID = "************************";
final String CLIENT_SECRET = "*******************";
// Create a state token to prevent request forgery.
// Store it in the session for later validation.
final String state = new BigInteger(130, new SecureRandom()).toString(32);
request.getSession().setAttribute("state", state);
// Read index.html into memory, and set the Client ID,
// Token State, and Application Name in the HTML before serving it.
try
{
return new Scanner(new File("index.html"), "UTF-8").useDelimiter("\\A").next()
.replaceAll("[{]{2}\\s*CLIENT_ID\\s*[}]{2}", CLIENT_ID).replaceAll("[{]{2}\\s*STATE\\s*[}]{2}", state)
.replaceAll("[{]{2}\\s*APPLICATION_NAME\\s*[}]{2}", APPLICATION_NAME);
}
catch (final FileNotFoundException e2)
{
// YTODO Auto-generated catch block
e2.printStackTrace();
}
if (!request.getParameter("state").equals(request.getSession().getAttribute("state")))
{
response.setStatus(401);
gson.toJson("Invalid state parameter.");
}
final String gPlusId = request.getParameter("gplus_id");
String code = null;
try
{
code = request.getReader().toString();
}
catch (final IOException e1)
{
// YTODO Auto-generated catch block
e1.printStackTrace();
}
try
{
// Upgrade the authorization code into an access and refresh token.
final GoogleTokenResponse tokenResponse = new GoogleAuthorizationCodeTokenRequest(TRANSPORT, JSON_FACTORY, CLIENT_ID,
CLIENT_SECRET, code, "postmessage").execute();
// Create a credential representation of the token data.
final GoogleCredential credential = new GoogleCredential.Builder().setJsonFactory(JSON_FACTORY).setTransport(TRANSPORT)
.setClientSecrets(CLIENT_ID, CLIENT_SECRET).build().setFromTokenResponse(tokenResponse);
// Check that the token is valid.
final Oauth2 oauth2 = new Oauth2.Builder(TRANSPORT, JSON_FACTORY, credential).build();
final Tokeninfo tokenInfo = oauth2.tokeninfo().setAccessToken(credential.getAccessToken()).execute();
// If there was an error in the token info, abort.
if (tokenInfo.containsKey("error"))
{
response.setStatus(401);
return gson.toJson(tokenInfo.get("error").toString());
}
// Make sure the token we got is for the intended user.
if (!tokenInfo.getUserId().equals(gPlusId))
{
response.setStatus(401);
return gson.toJson("Token's user ID doesn't match given user ID.");
}
// Make sure the token we got is for our app.
if (!tokenInfo.getIssuedTo().equals(CLIENT_ID))
{
response.setStatus(401);
return gson.toJson("Token's client ID does not match app's.");
}
// Store the token in the session for later use.
request.getSession().setAttribute("token", tokenResponse.toString());
return gson.toJson("Successfully connected user.");
}
catch (final TokenResponseException e)
{
response.setStatus(500);
return gson.toJson("Failed to upgrade the authorization code.");
}
catch (final IOException e)
{
response.setStatus(500);
return gson.toJson("Failed to read token data from Google. " + e.getMessage());
}
}
Here my Question is Am I going in right direction. Is it a proper way to connect java application with Google Login API. My Front View is working fine. When I click on google+ button, request also going to my controller. But There in backend side I am getting error. I am not pasting this error bacause error like NullPointerException or like that.
My Question is I am going in a proper way or not. If It is not, then what is the right way. Please help me.