简体   繁体   English

将Google登录按钮与Java应用程序集成时面临的问题

[英]Facing Issue While Integrating Google Login Button With Java Application

I am working on Hybris Technology. 我正在研究Hybris技术。 It is nothing but the Java only. 只是Java而已。 So I am trying to Integrate Google Login Button with my Java Application. 因此,我正在尝试将Google登录按钮与我的Java应用程序集成。

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 . 在这里,我使用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());
    }

}

Here my Question is Am I going in right direction. 我的问题是我是否朝着正确的方向前进。 Is it a proper way to connect java application with Google Login API. 这是将Java应用程序与Google Login API连接的正确方法。 My Front View is working fine. 我的前视图工作正常。 When I click on google+ button, request also going to my controller. 当我点击google +按钮时,请求也转到我的控制器。 But There in backend side I am getting error. 但是在后端,我得到了错误。 I am not pasting this error bacause error like NullPointerException or like that. 我没有粘贴此错误,原因是像NullPointerException之类的错误。

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. 请帮我。

You are making this very hard for yourself, and re-implementing too much. 您正在为自己做这些事情,并且重新实现了太多。

Read http://krams915.blogspot.se/2011/02/spring-security-3-openid-login-with_13.html 阅读http://krams915.blogspot.se/2011/02/spring-security-3-openid-login-with_13.html

You just need to ensure your Provider and UserDetailsService do what you need. 您只需要确保您的Provider和UserDetailsS​​ervice可以完成您需要的工作即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将Google登录按钮与Java应用程序集成时出现异常 - Getting Exception while Integrating Google Login button with Java Application 将Google Maps与Android应用程序集成-碎片问题 - Integrating Google Maps with an Android application - fragments issue 与Java应用程序集成时出现Bing转换器异常 - Bing translator exception while integrating with java application 使用Selenium WebDriver代码单击下拉按钮时遇到问题 - Facing issue while clicking dropdown button using selenium webdriver code 运行我的应用程序时,我在 Flutter 中遇到问题 - I am facing issue in Flutter while run my application 在Java中处理文件中的数据更改时遇到问题 - Facing issue while process the data changes in a file in java 使用 Keycloak Java 客户端创建用户时遇到问题 - Facing issue while creating user using Keycloak Java client 写入excel java时用spl字符替换字符串时遇到的问题 - facing issue in String replace with spl characters while writing to excel java 在 Java 中使用 Spark-BigQuery-Connector 时遇到问题 - Facing Issue while using Spark-BigQuery-Connector with Java 在Java和RestAsured中使用嵌套标签测试发布方法时遇到的问题 - Facing issue while testing post method with nested tags in Java and RestAsured
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM