com.google.gcloud.CredentialUtils.java Source code

Java tutorial

Introduction

Here is the source code for com.google.gcloud.CredentialUtils.java

Source

/*
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.gcloud;

import com.google.api.client.extensions.appengine.http.UrlFetchTransport;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.compute.ComputeCredential;
import com.google.api.client.googleapis.extensions.appengine.auth.oauth2.AppIdentityCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.repackaged.com.google.common.base.Preconditions;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.ServiceAccountCredentials;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.logging.Logger;
import java.util.Set;

/**
 * Utility class to assist with creating Credentials for AppEngine,
 * ComputeEngine and ServiceAccounts. There are a lot of options for obtaining Credentials
 * especially for Service Accounts. So, to simplify the life of Developers we will make this
 * idiomatic and use the idiom that Service Account Credentials are obtained from a JSON
 * file. The Environment variable GOOGLE_APPLICATION_CREDENTIALS points to the
 * Credential file. Also, we will use defaults for Json Factories and Transports.
 *
 * @author Perry Sakkaris
 */
public class CredentialUtils {
    private static final Logger LOG = Logger.getLogger(CredentialUtils.class.getName());
    private static final HttpTransport TRANSPORT = UrlFetchTransport.getDefaultInstance();
    private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();

    /**
     * Creates a GoogleCredential for a Service Account.
     * It requires that the
     * GOOGLE_APPLICATION_CREDENTIALS environment variable is correctly set. Scopes are not
     * required in the sense that you 'could' pass in null, but most RPC calls will fail if scopes
     * are not defines we require them here.
     * @param scopes (required)
     * @return a GoogleCredentials
     * @throws GeneralSecurityException on Transport error
     * @throws IOException on loading credentials error
     */
    public static GoogleCredential getServiceAccountCredential(final Set<String> scopes)
            throws GeneralSecurityException, IOException {

        Preconditions.checkArgument(scopes != null && scopes.size() > 0, "You must specify scopes");

        ServiceAccountCredentials serviceAccountCredentials = getDefaultServiceAccountCredentials();
        HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
        return new GoogleCredential.Builder().setJsonFactory(JSON_FACTORY).setTransport(transport)
                .setServiceAccountScopes(scopes).setServiceAccountId(serviceAccountCredentials.getClientEmail())
                .setServiceAccountPrivateKey(serviceAccountCredentials.getPrivateKey()).build();
    }

    /**
     * Creates a Compute Engine Credential.
     * @return ComputeCredential
     * @throws GeneralSecurityException on Transport error
     * @throws IOException if credential cannot be loaded
     */
    public static ComputeCredential getComputeEngineCredential() throws GeneralSecurityException, IOException {

        HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
        return new ComputeCredential.Builder(transport, JSON_FACTORY).build();
    }

    /**
     * Create AppEngine Credential.
     * @param scopes (required)
     * @return GoogleCredential
     * @throws IOException if credential cannot be loaded.
     */
    public static GoogleCredential getAppEngineCredential(final Set<String> scopes) throws IOException {

        Preconditions.checkArgument(scopes != null && scopes.size() > 0, "You must specify scopes");

        return new AppIdentityCredential.AppEngineCredentialWrapper(TRANSPORT, JSON_FACTORY).createScoped(scopes);
    }

    private static ServiceAccountCredentials getDefaultServiceAccountCredentials() throws IOException {

        GoogleCredentials credential = ServiceAccountCredentials.getApplicationDefault();
        if (credential instanceof ServiceAccountCredentials) {
            // require ServiceAccountCredentials
            // we can see how to rev in UserAccountCredentials if needed
            return (ServiceAccountCredentials) credential;
        }
        String message = String.format("Unrecognized credentials: %s", credential.getClass().getSimpleName());
        throw new IOException(message);
    }
}