【问题标题】:Why does Google OAuth 2.0 code-token Exchange returns "invalid_request"?为什么 Google OAuth 2.0 代码令牌交换返回“invalid_request”?
【发布时间】:2013-02-06 17:44:35
【问题描述】:

我已成功获得authorization_code。并得到"Error" : "invalid_request" 以响应authorization_code-token exchange
这是我获取 Google OAuth 令牌以换取 authentication_code 的 Java 代码:
(对 HTTP 请求使用 HttpComponents

String urlString = "https://accounts.google.com/o/oauth2/token";
String client_id = "<my_client_id>";
String client_secret = "<my_client_secret>";
String redirect_uri = "<my_redirect_url>";
String grant_type = "authorization_code";
HttpParams params = new BasicHttpParams();
params.setParameter("code", code);
params.setParameter("client_id", client_id);
params.setParameter("client_secret", client_secret);
params.setParameter("redirect_uri", redirect_uri);
params.setParameter("grant_type", grant_type);
HttpPost post = new HttpPost(urlString);
post.addHeader("Content-Type", "application/x-www-form-urlencoded");
post.setParams(params);
DefaultHttpClient httpClient = new DefaultHttpClient();
try {
    HttpResponse response = httpClient.execute(post);
    HttpEntity entity = response.getEntity();
    System.out.println(response.toString());
    DataInputStream in = new DataInputStream(entity.getContent());
    String line;
    while ((line = in.readLine()) != null) {
        System.out.println(line);
    }
}

得到以下错误响应:

HTTP/1.1 400 Bad Request [Cache-Control: no-cache, no-store, max-age=0, must-revalidate, Pragma: no-cache, Expires: Fri, 01 Jan 1990 00:00:00 GMT, Date: Thu, 21 Feb 2013 11:39:04 GMT, Content-Type: application/json, X-Content-Type-Options: nosniff, X-Frame-Options: SAMEORIGIN, X-XSS-Protection: 1; mode=block, Server: GSE, Transfer-Encoding: chunked]
{
  "error" : "invalid_request"
}

有什么方法可以知道究竟是什么导致了错误?
或者你能发现请求有什么问题吗?

【问题讨论】:

  • 对我来说看起来不错。有什么方法可以捕获实际的 HTTP 发布流量?根据我的经验,400 意味着语法错误。您的代码不包括您如何使用 urlString 进行“发布”,但我认为这很简单;也看不到 post.setHeader("Content-Type", "application/x-www-form-urlencoded");

标签: java oauth oauth-2.0 google-oauth


【解决方案1】:

虽然我没有使用 Apache 库的个人经验,但看起来参数是作为查询参数发送的,而不是作为发布的表单参数发送的。根据这个HttpClient Quick Start,它应该是这样的:

HttpPost httpPost = new HttpPost(urlString);
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("code", code));
nvps.add(new BasicNameValuePair("client_id", client_id));
nvps.add(new BasicNameValuePair("client_secret", client_secret));
nvps.add(new BasicNameValuePair("redirect_uri", redirect_uri));
nvps.add(new BasicNameValuePair("grant_type", grant_type));
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
HttpResponse response = httpclient.execute(httpPost);

【讨论】:

    猜你喜欢
    • 2014-07-23
    • 2011-08-05
    • 2012-12-20
    • 1970-01-01
    • 2014-05-12
    • 2013-08-17
    • 2019-03-16
    • 2012-01-29
    • 2012-08-05
    相关资源
    最近更新 更多