use of com.google.api.client.util.Beta in project google-api-java-client by google.
the class GoogleCredential method fromStreamServiceAccount.
@Beta
private static GoogleCredential fromStreamServiceAccount(GenericJson fileContents, HttpTransport transport, JsonFactory jsonFactory) throws IOException {
String clientId = (String) fileContents.get("client_id");
String clientEmail = (String) fileContents.get("client_email");
String privateKeyPem = (String) fileContents.get("private_key");
String privateKeyId = (String) fileContents.get("private_key_id");
if (clientId == null || clientEmail == null || privateKeyPem == null || privateKeyId == null) {
throw new IOException("Error reading service account credential from stream, " + "expecting 'client_id', 'client_email', 'private_key' and 'private_key_id'.");
}
PrivateKey privateKey = privateKeyFromPkcs8(privateKeyPem);
Collection<String> emptyScopes = Collections.emptyList();
Builder credentialBuilder = new GoogleCredential.Builder().setTransport(transport).setJsonFactory(jsonFactory).setServiceAccountId(clientEmail).setServiceAccountScopes(emptyScopes).setServiceAccountPrivateKey(privateKey).setServiceAccountPrivateKeyId(privateKeyId);
String tokenUri = (String) fileContents.get("token_uri");
if (tokenUri != null) {
credentialBuilder.setTokenServerEncodedUrl(tokenUri);
}
String projectId = (String) fileContents.get("project_id");
if (projectId != null) {
credentialBuilder.setServiceAccountProjectId(projectId);
}
// Don't do a refresh at this point, as it will always fail before the scopes are added.
return credentialBuilder.build();
}
use of com.google.api.client.util.Beta in project google-api-java-client by google.
the class GoogleCredential method executeRefreshToken.
@Override
@Beta
protected TokenResponse executeRefreshToken() throws IOException {
if (serviceAccountPrivateKey == null) {
return super.executeRefreshToken();
}
// service accounts: no refresh token; instead use private key to request new access token
JsonWebSignature.Header header = new JsonWebSignature.Header();
header.setAlgorithm("RS256");
header.setType("JWT");
header.setKeyId(serviceAccountPrivateKeyId);
JsonWebToken.Payload payload = new JsonWebToken.Payload();
long currentTime = getClock().currentTimeMillis();
payload.setIssuer(serviceAccountId);
payload.setAudience(getTokenServerEncodedUrl());
payload.setIssuedAtTimeSeconds(currentTime / 1000);
payload.setExpirationTimeSeconds(currentTime / 1000 + 3600);
payload.setSubject(serviceAccountUser);
payload.put("scope", Joiner.on(' ').join(serviceAccountScopes));
try {
String assertion = JsonWebSignature.signUsingRsaSha256(serviceAccountPrivateKey, getJsonFactory(), header, payload);
TokenRequest request = new TokenRequest(getTransport(), getJsonFactory(), new GenericUrl(getTokenServerEncodedUrl()), "urn:ietf:params:oauth:grant-type:jwt-bearer");
request.put("assertion", assertion);
return request.execute();
} catch (GeneralSecurityException exception) {
IOException e = new IOException();
e.initCause(exception);
throw e;
}
}
use of com.google.api.client.util.Beta in project google-api-java-client by google.
the class MediaHttpUploader method serverErrorCallback.
/**
* {@link Beta} <br/>
* The call back method that will be invoked on a server error or an I/O exception during
* resumable upload inside {@link #upload}.
*
* <p>
* This method changes the current request to query the current status of the upload to find how
* many bytes were successfully uploaded before the server error occurred.
* </p>
*/
@Beta
void serverErrorCallback() throws IOException {
Preconditions.checkNotNull(currentRequest, "The current request should not be null");
// Query the current status of the upload by issuing an empty PUT request on the upload URI.
currentRequest.setContent(new EmptyContent());
currentRequest.getHeaders().setContentRange("bytes */" + mediaContentLengthStr);
}
use of com.google.api.client.util.Beta in project google-api-java-client by google.
the class GoogleCredential method fromStream.
/**
* {@link Beta} <br/>
* Return a credential defined by a Json file.
*
* @param credentialStream the stream with the credential definition.
* @param transport the transport for Http calls.
* @param jsonFactory the factory for Json parsing and formatting.
* @return the credential defined by the credentialStream.
* @throws IOException if the credential cannot be created from the stream.
*/
@Beta
public static GoogleCredential fromStream(InputStream credentialStream, HttpTransport transport, JsonFactory jsonFactory) throws IOException {
Preconditions.checkNotNull(credentialStream);
Preconditions.checkNotNull(transport);
Preconditions.checkNotNull(jsonFactory);
JsonObjectParser parser = new JsonObjectParser(jsonFactory);
GenericJson fileContents = parser.parseAndClose(credentialStream, OAuth2Utils.UTF_8, GenericJson.class);
String fileType = (String) fileContents.get("type");
if (fileType == null) {
throw new IOException("Error reading credentials from stream, 'type' field not specified.");
}
if (USER_FILE_TYPE.equals(fileType)) {
return fromStreamUser(fileContents, transport, jsonFactory);
}
if (SERVICE_ACCOUNT_FILE_TYPE.equals(fileType)) {
return fromStreamServiceAccount(fileContents, transport, jsonFactory);
}
throw new IOException(String.format("Error reading credentials from stream, 'type' value '%s' not recognized." + " Expecting '%s' or '%s'.", fileType, USER_FILE_TYPE, SERVICE_ACCOUNT_FILE_TYPE));
}
use of com.google.api.client.util.Beta in project google-api-java-client by google.
the class GoogleCredential method privateKeyFromPkcs8.
@Beta
private static PrivateKey privateKeyFromPkcs8(String privateKeyPem) throws IOException {
Reader reader = new StringReader(privateKeyPem);
Section section = PemReader.readFirstSectionAndClose(reader, "PRIVATE KEY");
if (section == null) {
throw new IOException("Invalid PKCS8 data.");
}
byte[] bytes = section.getBase64DecodedBytes();
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
Exception unexpectedException = null;
try {
KeyFactory keyFactory = SecurityUtils.getRsaKeyFactory();
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return privateKey;
} catch (NoSuchAlgorithmException exception) {
unexpectedException = exception;
} catch (InvalidKeySpecException exception) {
unexpectedException = exception;
}
throw OAuth2Utils.exceptionWithCause(new IOException("Unexpected exception reading PKCS data"), unexpectedException);
}
Aggregations