[英]Google Email Settings api using OAuth 2.0 service account in java
[英]Unable to get token using Google APIs [google-oauth-java-client-1.12.0-beta] for service account flow
我使用Google API(版本為google-oauth-java-client-1.12.0-beta)來獲取OAuth2訪問令牌但返回“invalid_grant”。 參考: https : //developers.google.com/accounts/docs/OAuth2ServiceAccount
這是代碼:
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 = "user1@gmail.com";
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();
}
}
結果:
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)
這里有什么問題? 任何暗示將不勝感激。
在Google服務和Google API客戶端庫上使用服務帳戶時,您不必自己創建簽名並構建JWT令牌,因為有讀取使用的實用程序類只需通過OAuth 2.0執行服務帳戶授權。
但是,除了Google Drive文檔中包含多種編程語言的詳細說明和代碼示例之外,這一點並沒有得到很好的記錄。 您應該閱讀: https : //developers.google.com/drive/service-accounts#google_apis_console_project_service_accounts
您的代碼存在一些問題:
<some-id>@developer.gserviceaccount.com
(是的是電子郵件而不是客戶端ID,我知道這很奇怪) principal
,但當然不能在Gmail帳戶上執行此操作,僅限於您的域已被管理員授予訪問權限的Google Apps帳戶,因此在您的情況下:請勿設置它。 下面是使用Java的OAuth 2.0 w / Service帳戶的代碼示例。
注意:您還需要下載URL Shortener庫 。
/** Email of the Service Account */
private static final String SERVICE_ACCOUNT_EMAIL = "<some-id>@developer.gserviceaccount.com";
/** Path to the Service Account's Private Key file */
private static final String SERVICE_ACCOUNT_PKCS12_FILE_PATH = "/path/to/<public_key_fingerprint>-privatekey.p12";
/**
* Build and returns a URL Shortner service object authorized with the service accounts.
*
* @return URL Shortner service object that is ready to make requests.
*/
public static Drive getDriveService() throws GeneralSecurityException, IOException, URISyntaxException {
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(UrlshortenerScopes.URLSHORTENER)
.setServiceAccountPrivateKeyFromP12File(
new java.io.File(SERVICE_ACCOUNT_PKCS12_FILE_PATH))
.build();
Urlshortener service = new Urlshortener.Builder(httpTransport, jsonFactory, null)
.setHttpRequestInitializer(credential).build();
return service;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.