将Google登录按钮与Java应用程序集成时面临的问题 [英] Facing Issue While Integrating Google Login Button With Java Application

查看:74
本文介绍了将Google登录按钮与Java应用程序集成时面临的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究 Hybris 技术.只是Java而已.因此,我正在尝试将Google登录按钮与我的Java应用程序集成在一起.

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

前部-

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

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());
    }

}

在这里,我的问题是我是否朝着正确的方向前进.这是将Java应用程序与Google Login API连接的正确方法.我的前视图工作正常.当我点击google +按钮时,请求也转到我的控制器.但是在后端,我得到了错误.我没有粘贴此错误是因为类似NullPointerException之类的错误.

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.

推荐答案

您正在为自己做这件事非常困难,并且重新实现得太多.

You are making this very hard for yourself, and re-implementing too much.

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

您只需要确保Provider和UserDetailsS​​ervice可以满足您的需求.

You just need to ensure your Provider and UserDetailsService do what you need.

这篇关于将Google登录按钮与Java应用程序集成时面临的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆