访问Google oAuth,提供无效的grant_type(错误请求)

时间:2015-10-03 05:03:33

标签: java oauth google-api google-calendar-api google-oauth2

我在SO中搜索了很多,浏览了许多关于同一错误的问题,应用了他们建议的任何内容,但结果没有任何结果。因此写在这里。

我正在学习如何拨打Google API(比如Google Calendar API)。我正在浏览谷歌开发者教程 https://developers.google.com/identity/protocols/OAuth2ServiceAccount

所以我在google中创建了一个服务帐户,创建了凭据(我想从我自己的应用程序中调用Google API)。之后我创建了JWT,用谷歌共享的私钥烧录了我的JWT,然后进行REST POST调用以获得oAuth。这是我的代码

public class TestGoogleAPI {

public static void main(String[] args) throws Exception{
    String header = "{\"alg\":\"RS256\",\"typ\":\"JWT\"}";
    long time = Calendar.getInstance().getTimeInMillis()/1000;

    String claimSet = "{\"iss\":\"xxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com\"," +
                "\"scope\":\"https://www.googleapis.com/auth/calendar\"," +
                "\"aud\":\"https://www.googleapis.com/oauth2/v3/token\"," +
                "\"exp\":"+ (time+3600) +"," +
                "\"iat\":" + time +"}";


    String base64Header = new String(Base64.encodeBase64(header.getBytes()),"UTF-8");
    String base64ClaimSet = new String(Base64.encodeBase64(claimSet.getBytes()),"UTF-8");

    String input = base64Header + "." + base64ClaimSet;

    File f = new File("D:/downloads/privatekey.txt");
    FileInputStream fis = new FileInputStream(f);
    DataInputStream dis = new DataInputStream(fis);
    byte[] keyBytes = new byte[(int)f.length()];
    dis.readFully(keyBytes);
    dis.close();
    byte[] key = Base64.decodeBase64(keyBytes);

    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(key);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PrivateKey privatekey =  kf.generatePrivate(spec);

    Signature signature = Signature.getInstance("SHA256withRSA"); 
    signature.initSign(privatekey);
    signature.update(input.getBytes());
    String base64Sign = new String(Base64.encodeBase64(signature.sign()),"UTF-8");

    doHttpPost("https://www.googleapis.com/oauth2/v3/token", input + "." + base64Sign);
}

public static void doHttpPost(String urlStr, String assertion) throws Exception{
    URL url = new URL(urlStr);
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod("POST");
      conn.setDoOutput(true);
      conn.setDoInput(true);
      conn.setUseCaches(false);
      conn.setAllowUserInteraction(false);
      conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

      OutputStream out = conn.getOutputStream();
      Writer writer = new OutputStreamWriter(out, "UTF-8");
      writer.write("grant_type");
      writer.write("=");
      writer.write(URLEncoder.encode("urn:ietf:params:oauth:grant-type:jwt-bearer", "UTF-8"));
      writer.write("&");
      writer.write("assertion");
      writer.write("=");
      writer.write(URLEncoder.encode(assertion, "UTF-8"));
      writer.close();
      out.close();

      if (conn.getResponseCode() != 200) {
          System.out.println(conn.getResponseMessage());
      }

      BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      StringBuilder sb = new StringBuilder();
      String line;
      while ((line = rd.readLine()) != null) {
        sb.append(line);
      }
      rd.close();

      conn.disconnect();
      System.out.println(sb.toString());
}

}

我收到400(不良请求)。我在" Chrome的高级休息客户端"中尝试了相同的操作,但结果相同,无效的grant_type(错误的请求)。

{
   error: "invalid_grant"
   error_description: "Bad Request"
}

我在这里遗漏了什么。请帮帮我

由于

1 个答案:

答案 0 :(得分:0)

最后我得到了决议。当我编码header和claimset时,我正在进行base64编码,而不是base64safeURL encoidng。更换后

Base64.encodeBase64(some_data);

Base64.encodeBase64URLSafe(some_data);

在上述代码的所有事件中,一切正常。我正在获取访问令牌并能够使用oAuth令牌

来点击谷歌API