【问题标题】:Google's oauth endpoint is returning a 'Bad Request'... but why?Google 的 oauth 端点正在返回“错误请求”……但为什么呢?
【发布时间】:2013-10-28 09:45:32
【问题描述】:

https://accounts.google.com/o/oauth2/token 请求令牌时浪费了大量时间在谷歌上搜索“错误请求”的可能原因后,我决定问为什么这段代码只能获得“错误请求”响应服务器...

String url = "https://accounts.google.com/o/oauth2/token";
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setChunkedStreamingMode(0);
con.setRequestMethod("POST");
con.setRequestProperty("Host", "accounts.google.com");
con.setRequestProperty("Content-Type",
        "application/x-www-form-urlencoded");
con.setRequestProperty("code", authCode);
con.setRequestProperty("client_id",
        "[CLIENT_ID]");
con.setRequestProperty("client_secret", "[CLIENT_SECRET");
con.setRequestProperty("redirect_uri",
        "http://localhost:8080/login");
con.setRequestProperty("grant_type", "authorization_code");

// Send post request
con.setDoOutput(true);

我确实必须设置con.setChunkedStreamingMode(0),因为服务器返回了与内容长度相关的错误。

有什么想法吗? 是否有必要将有效载荷放在一行中?如何?

【问题讨论】:

    标签: java oauth oauth-2.0 httpsurlconnection


    【解决方案1】:

    我认为 HTTP 400(错误请求)的原因是您将 codeclient_idclient_secretgrant_typeredirect_uri 作为 HTTP 请求标头发送到您需要发送它们的地方作为 HTTP POST 请求正文中的查询参数(根据Google OAuth2InstalledApp docs)。

    查看Using java.net.URLConnection to fire and handle HTTP requests,了解如何发送 HTTP POST 的一个很好的示例。您需要将codeclient_id 等作为查询字符串写入正文中:

    // partial example only: only code and client_id are included
    String query = String.format("code=%s&client_id=%s", code, client_id);  
    OutputStream out = con.getOutputStream();
    out.write(query.getBytes("UTF-8"));
    

    从 Google OAuth2 文档中,示例 HTTP POST 请求可能如下所示:

    POST /o/oauth2/token HTTP/1.1
    Host: accounts.google.com
    Content-Type: application/x-www-form-urlencoded
    
    code=4/v6xr77ewYqhvHSyW6UJ1w7jKwAzu&
    client_id=8819981768.apps.googleusercontent.com&
    client_secret={client_secret}&
    redirect_uri=https://oauth2-login-demo.appspot.com/code&
    grant_type=authorization_code
    

    【讨论】:

    • 我认为你是对的。嗯,我还有一个问题......只有特定的 oauth 属性必须在该查询字符串上引用?还是我必须在那里设置内容类型?
    • 只是查询字符串参数。 Content-Type 需要设置为 HTTP 标头。我已更新我的答案以显示来自 Google 文档的示例 HTTP POST。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-02
    • 2019-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    相关资源
    最近更新 更多