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或類似的錯誤。
我的問題是我以正確的方式進行或沒有。如果不是,那麼什麼是正確的方法。請幫幫我。