我正在尝试获取 OAuth2 令牌,以便我可以在 Authorization Header 的 GET BUCKET 方法中使用它。
我正在通过以下链接中提到的 grant_type 和断言来获取令牌: https ://developers.google.com/accounts/docs/OAuth2ServiceAccount#libraries
是什么导致 invalid_grant 响应?
谢谢!
我正在尝试获取 OAuth2 令牌,以便我可以在 Authorization Header 的 GET BUCKET 方法中使用它。
我正在通过以下链接中提到的 grant_type 和断言来获取令牌: https ://developers.google.com/accounts/docs/OAuth2ServiceAccount#libraries
是什么导致 invalid_grant 响应?
谢谢!
解决了这个问题。我为内容中需要的“过期”分配了一些不同的值。现在它适用于
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。
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;
}