OpenId Connect to Google给了我Http 400

时间:2014-11-09 20:38:43

标签: java servlets google-api openid-connect

我尝试使用OAuth 2.0访问Google API

但是当我尝试获取令牌

时,我总是收到http 400

我使用Tomcat8和Java SDK 8 我不知道出了什么问题。

private void sendPost(
        final String code, 
        final String clientId, 
        final String clientSecret, 
        final String redirectUri,
        final String grantType) throws Exception {

    String url = "https://accounts.google.com/o/oauth2/token";

    StringBuffer strb = new StringBuffer();
    strb.append("code=" + code);
    strb.append("&client_id=" + clientId);
    strb.append("&client_secret=" + clientSecret);
    strb.append("&redirect_uri=" + redirectUri);
    strb.append("&grant_type=" + grantType);

    String urlParameters = strb.toString();

    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

    con.setRequestMethod("POST");
    con.setDoOutput(true);
    con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
    con.setRequestProperty("Content-Length", String.valueOf(urlParameters.length()));


    // Send post request
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + urlParameters);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(new InputStreamReader(
            con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    // print result
    System.out.println(response.toString());

}

我的输出如下似乎所有参数都可以。

Sending 'POST' request to URL : https://accounts.google.com/o/oauth2/token
Post parameters : code=<code>.InoAg9JcLi0boiIBeO6P2m94pmoskwI&client_id=<clientid>.apps.googleusercontent.com&client_secret=<secret>&redirect_uri=http://localhost:8080/Oauth/connect&grant_type=authorization_code
Response Code : 400

1 个答案:

答案 0 :(得分:0)

  1. 您想要对参数进行网址编码
  2. 我认为Google不再支持redirect_uri指向“localhost”,因此建议您在与令牌端点请求上显示的redirect_uri不同的redirect_uri上获得“代码”