Search in sources :

Example 1 with Beta

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();
}
Also used : PrivateKey(java.security.PrivateKey) IOException(java.io.IOException) Beta(com.google.api.client.util.Beta)

Example 2 with Beta

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;
    }
}
Also used : JsonWebSignature(com.google.api.client.json.webtoken.JsonWebSignature) GeneralSecurityException(java.security.GeneralSecurityException) TokenRequest(com.google.api.client.auth.oauth2.TokenRequest) GenericUrl(com.google.api.client.http.GenericUrl) IOException(java.io.IOException) JsonWebToken(com.google.api.client.json.webtoken.JsonWebToken) Beta(com.google.api.client.util.Beta)

Example 3 with Beta

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);
}
Also used : EmptyContent(com.google.api.client.http.EmptyContent) Beta(com.google.api.client.util.Beta)

Example 4 with Beta

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));
}
Also used : GenericJson(com.google.api.client.json.GenericJson) JsonObjectParser(com.google.api.client.json.JsonObjectParser) IOException(java.io.IOException) Beta(com.google.api.client.util.Beta)

Example 5 with Beta

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);
}
Also used : PrivateKey(java.security.PrivateKey) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) StringReader(java.io.StringReader) PemReader(com.google.api.client.util.PemReader) Reader(java.io.Reader) StringReader(java.io.StringReader) FileReader(java.io.FileReader) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) Section(com.google.api.client.util.PemReader.Section) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyFactory(java.security.KeyFactory) Beta(com.google.api.client.util.Beta)

Aggregations

Beta (com.google.api.client.util.Beta)5 IOException (java.io.IOException)4 GeneralSecurityException (java.security.GeneralSecurityException)2 PrivateKey (java.security.PrivateKey)2 TokenRequest (com.google.api.client.auth.oauth2.TokenRequest)1 EmptyContent (com.google.api.client.http.EmptyContent)1 GenericUrl (com.google.api.client.http.GenericUrl)1 GenericJson (com.google.api.client.json.GenericJson)1 JsonObjectParser (com.google.api.client.json.JsonObjectParser)1 JsonWebSignature (com.google.api.client.json.webtoken.JsonWebSignature)1 JsonWebToken (com.google.api.client.json.webtoken.JsonWebToken)1 PemReader (com.google.api.client.util.PemReader)1 Section (com.google.api.client.util.PemReader.Section)1 FileReader (java.io.FileReader)1 Reader (java.io.Reader)1 StringReader (java.io.StringReader)1 KeyFactory (java.security.KeyFactory)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)1 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)1