2014-02-18 26 views
0

我正在研究Hybris技术。它只是Java而已。所以我正在尝试将Google登录按钮与我的Java应用程序集成。我正在关注this tutorial。这里是我的代码,我在做什么在将Google登录按钮与Java应用程序集成时面临问题

接待部分 -

<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> 

这里我使用AJAX调用我的控制器功能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()); 
    } 

} 

在这里我的问题是我正确的方向。这是将Java应用程序与Google Login API连接的正确方法。我的前视工作正常。当我点击谷歌+按钮,请求也去我的控制器。但是在后端我有错误。我不粘贴这个错误,像NullPointerException或类似的错误。

我的问题是我以正确的方式进行或没有。如果不是,那么什么是正确的方法。请帮帮我。

回答

相关问题