Keine token-Verwendung von Google-APIs [google-oauth-java-client-1.12.0-beta] für service-Konto fließen
Ich bin mit Google APIs (version google-oauth-java-client-1.12.0-beta), um eine OAuth2 access token aber wieder "invalid_grant".
Ref: https://developers.google.com/accounts/docs/OAuth2ServiceAccount
Hier ist der code:
import com.google.api.client.auth.jsontoken.JsonWebSignature;
import com.google.api.client.auth.jsontoken.JsonWebToken;
import com.google.api.client.auth.jsontoken.RsaSHA256Signer;
import com.google.api.client.auth.oauth2.TokenRequest;
import com.google.api.client.auth.oauth2.TokenResponse;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.Clock;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
public class TestClient
{
private static PrivateKey getPrivateKey(String keyFile, String alias, String password)
throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException
{
KeyStore keystore = KeyStore.getInstance("PKCS12");
keystore.load(new FileInputStream(keyFile), password.toCharArray());
PrivateKey privateKey = (PrivateKey) keystore.getKey(alias, password.toCharArray());
return privateKey;
}
public static void main(String[] args)
throws GeneralSecurityException, IOException
{
String password = "notasecret";
String alias = "privatekey";
String keyFile = "<private key file>.p12";
String serviceAccountScopes = "https://www.googleapis.com/auth/urlshortener";
String serviceAccountUser = "[email protected]";
String serviceAccountId = "<a/c id>.apps.googleusercontent.com";
JsonWebSignature.Header header = new JsonWebSignature.Header();
header.setAlgorithm("RS256");
header.setType("JWT");
JsonWebToken.Payload payload = new JsonWebToken.Payload(Clock.SYSTEM);
long currentTime = Clock.SYSTEM.currentTimeMillis();
payload.setIssuer(serviceAccountId)
.setAudience("https://accounts.google.com/o/oauth2/token")
.setIssuedAtTimeSeconds(currentTime / 1000)
.setExpirationTimeSeconds(currentTime / 1000 + 3600)
.setPrincipal(serviceAccountUser);
payload.put("scope", serviceAccountScopes);
System.out.println(payload.toPrettyString());
PrivateKey serviceAccountPrivateKey = getPrivateKey(keyFile, alias, password);
String assertion = RsaSHA256Signer.sign(serviceAccountPrivateKey, getJsonFactory(), header, payload);
TokenRequest request = new TokenRequest(getTransport(), getJsonFactory(), new GenericUrl(getTokenServerEncodedUrl()), "assertion");
request.put("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer");
request.put("assertion", assertion);
TokenResponse resp = request.execute();
System.out.println("token : " + resp.getAccessToken());
}
private static String getTokenServerEncodedUrl()
{
return "https://accounts.google.com/o/oauth2/token";
}
private static JsonFactory getJsonFactory()
{
return new JacksonFactory();
}
private static HttpTransport getTransport()
{
return new NetHttpTransport();
}
}
Ergebnis:
Exception in thread "main" com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
{
"error" : "invalid_grant"
}
at com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:103)
at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:303)
at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:323)
Was ist hier das problem? jeder Hinweis wäre willkommen.
Du musst angemeldet sein, um einen Kommentar abzugeben.
Bei der Verwendung von Service-Konten auf Google-Dienste und der Google APIs-Client-Bibliothek, die Sie nicht haben, um eine Signatur zu erstellen und zu konstruieren, die JWT Token selbst, da es read-to-use-utility-Klassen, die zu führen Sie einfach die Service-Konten Autorisierung über OAuth 2.0.
Dies ist jedoch nicht sehr gut dokumentiert, außer auf das Google Drive-Dokumentation enthält ausführliche Erklärung und Beispielcode in mehreren Programmiersprachen. Sollten Sie Lesen:
https://developers.google.com/drive/service-accounts#google_apis_console_project_service_accounts
Einige Probleme mit Ihrem code:
<some-id>@developer.gserviceaccount.com
(ja, die E-Mail anstelle der Client-ID, ich weiß, es ist seltsam)principal
wenn dabei Google Apps-domain-Breiten-delegation aber Sie können nicht, dass auf Gmail-Konten natürlich nur auf Google-Apps-Konten, deren Domäne haben Sie Zugriff auf die von einem administrator also in deinem Fall: nicht festgelegt werden.Unten ist der Beispielcode für OAuth 2.0 w/Service-Konten in Java.
Hinweis: Sie müssen auch zum download der URL-Shortener-Bibliothek.