Google云端存储服务帐户出现Invalid_grant错误

时间:2013-04-24 14:55:10

标签: oauth-2.0 google-cloud-storage

我正在尝试获取OAuth2令牌,以便我可以在授权标头中的GET BUCKET方法中使用它。

我正在传递grant_type和断言,如以下链接中所述获取令牌: https://developers.google.com/accounts/docs/OAuth2ServiceAccount#libraries

导致invalid_grant响应的原因是什么?

谢谢!

2 个答案:

答案 0 :(得分:1)

解决了这个问题。我正在为内容中需要的“到期”分配一些不同的值。 现在它适用于

long currenttime = System.currentTimeMillis();
long now = currenttime / 1000;
long expiration = currenttime / 1000 + 3600;

以及以下

String temp = JWTBase64Header + "." + JWTBase64Content;
byte[] JWTSignatureInput = temp.getBytes("UTF8");

final String keyFile = "xx9d9xxxxxx12cd99fxxxx60bxxxxx1-privatekey.p12";
final String keyPassword = "notasecret";
PrivateKey pkcsKey = loadKeyFromPkcs12(keyFile, keyPassword.toCharArray());
String JWTBase64Signature = signData(pkcsKey, new String(JWTSignatureInput, "UTF8"));

String params = "grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion="+JWTBase64Header + "." + JWTBase64Content + "."
        + JWTBase64Signature;

URL url = new URL("https://accounts.google.com/o/oauth2/token");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", Integer.toString(params.getBytes().length));

//Send request

  DataOutputStream wr = new DataOutputStream (
              conn.getOutputStream ());
  wr.writeBytes (params.toString());
  wr.flush ();
  wr.close ();

现在只需从连接获取输入流并解析它以获取access_token。

答案 1 :(得分:0)

private static PrivateKey loadKeyFromPkcs12(String filename, char[] password)
        throws Exception {
    FileInputStream fis = new FileInputStream(
            "NewFolder/" + filename);

    KeyStore ks = KeyStore.getInstance("PKCS12");
    try {
        ks.load(fis, password);
    } catch (IOException e) {
        if (e.getCause() != null
                && e.getCause() instanceof UnrecoverableKeyException) {
            System.err.println("Incorrect password");
        }
        throw e;
    }
    return (PrivateKey) ks.getKey("privatekey", password);
}

private static String signData(PrivateKey key, String data)
        throws Exception {
    Signature signer = Signature.getInstance("SHA256withRSA");
    signer.initSign(key);
    signer.update(data.getBytes("UTF8"));
    byte[] rawSignature = signer.sign();
    String encodedSignature = new String(Base64.encodeBase64URLSafe(rawSignature));
    return encodedSignature;
}