用于获取访问令牌的Google oauth java客户端失败,并显示“400 Bad Request {”error“:”invalid_request“}”
作者:互联网
我正在使用此处显示的“Web服务器应用程序”示例.在我的回调servlet中,我想要检索一个访问令牌,但我无法成功地执行它.
以下是我的代码
@Override
protected String getUserId(HttpServletRequest req) throws ServletException, IOException {
// return user ID
Iterator<String> iterator = req.getParameterMap().keySet().iterator();
while (iterator.hasNext()) {
String string = iterator.next();
System.out.println(string+"---++--"+req.getParameter(string));
}
GoogleAuthorizationCodeTokenRequest newTokenRequest = new GoogleAuthorizationCodeFlow.Builder(new NetHttpTransport(), new JacksonFactory(),
"2XXXXXX7218.apps.googleusercontent.com", "KugD_XXX_7vqnGZVXXXXX1M",
Collections.singleton("https://gdata.youtube.com"))
.build().newTokenRequest(req.getParameter("code"));
//GoogleAuth
GoogleTokenResponse token = newTokenRequest.setRedirectUri("/").execute();
String accessToken = token.getAccessToken();
System.out.println("accesstoken:"+accessToken);
return "";
}
运行此代码后,我收到以下错误
com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
{
"error" : "invalid_request"
}
简而言之,我得到“代码”参数(请求代码)我不知道如何将其转换为Access令牌.
我已经看过了
Google API – request for token from Oauth2 returns “invalid_request”
Google OAuth 2: response_type error on token request但是在我的代码中我无法使用
编辑
谷歌API不适合我,所以我编写了以下代码,而不使用任何库
URL url = new URL("https://accounts.google.com/o/oauth2/token");
connection = (HttpURLConnection) url.openConnection();
String urlParameters = "code=" + req.getParameter("code") + "&client_id=29852.apps.googleusercontent.com&client_secret=KugD_LVi_7vqnssssxxxNRBz1M"+
"&redirect_uri=https://flixomnia.com/oauth2callback&grant_type=authorization_code&scope=https://gdata.youtube.com&response_type=token";
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Authorization", "Bearer 4/q3Xh_pJI458XXXXXXXkh-lxe3-8.cmaD6o7V5BkQXE-XXXXX-edgI");
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("X-GData-Key", "key=AI39siXXXXXXM7tyHBvXEM1lLcORetit6QSArQ3sjelBxXXXXXXtgLSPdZPxvsF_vkntOQMnAEYAuVFqhN7oUw");
connection.setRequestProperty("GData-Version", "2");
connection.setUseCaches(false);
//com.google.gdata.client.youtube.YouTubeService service = new com.google.gdata.client.youtube.YouTubeService("","");
//YouTubeMediaGroup g = new YouTubeMediaGroup();
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
InputStream inputStream = connection.getInputStream();
byte[] b = new byte[1024];
while (inputStream.read(b) != -1) {
System.out.print(new String(b));
}
System.out.println("");
wr.close();
connection.disconnect();
但我仍然得到以下错误
{ "error" : "invalid_request"}
java.io.IOException: Server returned HTTP response code: 400 for URL: https://accounts.google.com/o/oauth2/token
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1615)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
at com.broadcastr.servlets.YouTubeCallbackService.getUserId(YouTubeCallbackService.java:168)
at com.google.api.client.extensions.servlet.auth.oauth2.AbstractAuthorizationCodeCallbackServlet.doGet(AbstractAuthorizationCodeCallbackServlet.java:130)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1001)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
解决方法:
>在上面的初始代码中的setRedirectUri方法中获取访问令牌,redirect_uri未正确设置.应使用在客户端注册时指定的redirect_uri.
>在EDIT代码中,在将所需参数发送到访问令牌端点时,还会发送不受支持的参数response_type以及请求.删除response_type参数应该可以解决问题.
此外,根据OAuth2 RFC draft,如果请求使用多个机制来验证客户端,则访问令牌端点也可能使invalid_request错误.因此,删除URLConnection的Authorization标头也应该可以解决问题.
标签:java,oauth-2-0,google-oauth 来源: https://codeday.me/bug/20190729/1570146.html