Java Code Examples for com.google.auth.oauth2.GoogleCredentials#fromStream()

The following examples show how to use com.google.auth.oauth2.GoogleCredentials#fromStream() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractInteropTest.java    From grpc-java with Apache License 2.0 9 votes vote down vote up
/** Sends a unary rpc with raw oauth2 access token credentials. */
public void oauth2AuthToken(String jsonKey, InputStream credentialsStream, String authScope)
    throws Exception {
  GoogleCredentials utilCredentials =
      GoogleCredentials.fromStream(credentialsStream);
  utilCredentials = utilCredentials.createScoped(Arrays.asList(authScope));
  AccessToken accessToken = utilCredentials.refreshAccessToken();

  OAuth2Credentials credentials = OAuth2Credentials.create(accessToken);

  TestServiceGrpc.TestServiceBlockingStub stub = blockingStub
      .withCallCredentials(MoreCallCredentials.from(credentials));
  final SimpleRequest request = SimpleRequest.newBuilder()
      .setFillUsername(true)
      .setFillOauthScope(true)
      .build();

  final SimpleResponse response = stub.unaryCall(request);
  assertFalse(response.getUsername().isEmpty());
  assertTrue("Received username: " + response.getUsername(),
      jsonKey.contains(response.getUsername()));
  assertFalse(response.getOauthScope().isEmpty());
  assertTrue("Received oauth scope: " + response.getOauthScope(),
      authScope.contains(response.getOauthScope()));
}
 
Example 2
Source File: AbstractInteropTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
/** Sends a unary rpc with raw oauth2 access token credentials. */
public void oauth2AuthToken(String jsonKey, InputStream credentialsStream, String authScope)
    throws Exception {
  GoogleCredentials utilCredentials =
      GoogleCredentials.fromStream(credentialsStream);
  utilCredentials = utilCredentials.createScoped(Arrays.asList(authScope));
  AccessToken accessToken = utilCredentials.refreshAccessToken();

  OAuth2Credentials credentials = OAuth2Credentials.create(accessToken);

  TestServiceGrpc.TestServiceBlockingStub stub = blockingStub
      .withCallCredentials(MoreCallCredentials.from(credentials));
  final SimpleRequest request = SimpleRequest.newBuilder()
      .setFillUsername(true)
      .setFillOauthScope(true)
      .build();

  final SimpleResponse response = stub.unaryCall(request);
  assertFalse(response.getUsername().isEmpty());
  assertTrue("Received username: " + response.getUsername(),
      jsonKey.contains(response.getUsername()));
  assertFalse(response.getOauthScope().isEmpty());
  assertTrue("Received oauth scope: " + response.getOauthScope(),
      authScope.contains(response.getOauthScope()));
}
 
Example 3
Source File: GcsRepositoryAutoConfiguration.java    From hawkbit-extensions with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * GSC storage service
 * 
 * @param gcsProperties
 *            properties to initialize GCS storage service
 * @return the {@link Storage} if no other {@link Storage} bean is registered.
 */
@Bean
@ConditionalOnMissingBean
public Storage gcsStorage(final GcsRepositoryProperties gcsProperties) {
    if (gcsProperties.getCredentialsLocation() != null) {
        try {
            Credentials credentials = GoogleCredentials
                    .fromStream(gcsProperties.getCredentialsLocation().getInputStream());
            return StorageOptions.newBuilder().setCredentials(credentials)
                    .setProjectId(gcsProperties.getProjectId()).build().getService();
        } catch (IOException e) {
            throw new GcpInitialisationFailedException(e);
        }
    } else {
        return StorageOptions.getDefaultInstance().getService();
    }
}
 
Example 4
Source File: GoogleKms.java    From halyard with Apache License 2.0 6 votes vote down vote up
private static GoogleCredentials loadKmsCredential(String jsonPath) throws IOException {
  GoogleCredentials credentials;
  if (!jsonPath.isEmpty()) {
    FileInputStream stream = new FileInputStream(jsonPath);
    credentials = GoogleCredentials.fromStream(stream);
    log.info("Loaded kms credentials from " + jsonPath);
  } else {
    log.info("Using kms default application credentials.");
    credentials = GoogleCredentials.getApplicationDefault();
  }

  if (credentials.createScopedRequired()) {
    credentials = credentials.createScoped(CloudKMSScopes.all());
  }

  return credentials;
}
 
Example 5
Source File: AgentParser.java    From helios with Apache License 2.0 6 votes vote down vote up
private GoogleCredentials loadGoogleCredentials(
    final boolean useDefaultCredentials,
    final File credentialsFile)
    throws ArgumentParserException, IOException {

  if (useDefaultCredentials && credentialsFile != null) {
    final String msg = String.format("Cannot set both %s and %s",
        this.googleCloudCredentialsFile.getDest(),
        this.useGoogleDefaultApplicationCredentials.getDest());
    throw new IllegalArgumentException(msg);
  }

  if (useDefaultCredentials) {
    return GoogleCredentials.getApplicationDefault();
  }
  try (final FileInputStream stream = new FileInputStream(credentialsFile)) {
    return GoogleCredentials.fromStream(stream);
  }
}
 
Example 6
Source File: AbstractDockerMojo.java    From dockerfile-maven with Apache License 2.0 5 votes vote down vote up
/**
 * Attempt to load a GCR compatible RegistryAuthSupplier based on a few conditions:
 * <ol>
 * <li>First check to see if the environemnt variable DOCKER_GOOGLE_CREDENTIALS is set and points
 * to a readable file</li>
 * <li>Otherwise check if the Google Application Default Credentials can be loaded</li>
 * </ol>
 * Note that we use a special environment variable of our own in addition to any environment
 * variable that the ADC loading uses (GOOGLE_APPLICATION_CREDENTIALS) in case there is a need for
 * the user to use the latter env var for some other purpose in their build.
 *
 * @return a GCR RegistryAuthSupplier, or null
 * @throws IOException if an IOException occurs while loading the credentials
 */
@Nullable
private RegistryAuthSupplier googleContainerRegistryAuthSupplier() throws IOException {
  GoogleCredentials credentials = null;

  final String googleCredentialsPath = System.getenv("DOCKER_GOOGLE_CREDENTIALS");
  if (googleCredentialsPath != null) {
    final File file = new File(googleCredentialsPath);
    if (file.exists()) {
      try (FileInputStream inputStream = new FileInputStream(file)) {
        credentials = GoogleCredentials.fromStream(inputStream);
        getLog().info("Using Google credentials from file: " + file.getAbsolutePath());
      }
    }
  }

  // use the ADC last
  if (credentials == null) {
    try {
      credentials = GoogleCredentials.getApplicationDefault();
      getLog().info("Using Google application default credentials");
    } catch (IOException ex) {
      // No GCP default credentials available
      getLog().debug("Failed to load Google application default credentials", ex);
    }
  }

  if (credentials == null) {
    return null;
  }

  return ContainerRegistryAuthSupplier.forCredentials(credentials).build();
}
 
Example 7
Source File: BigQueryCredentialsSupplier.java    From spark-bigquery-connector with Apache License 2.0 5 votes vote down vote up
private static Credentials createCredentialsFromKey(String key) {
    try {
        return GoogleCredentials.fromStream(new ByteArrayInputStream(Base64.decodeBase64(key)));
    } catch (IOException e) {
        throw new UncheckedIOException("Failed to create Credentials from key", e);
    }
}
 
Example 8
Source File: FirebaseService.java    From zhcet-web with Apache License 2.0 5 votes vote down vote up
private void initializeFirebase() throws IOException {
    try {
        String messagingScope = "https://www.googleapis.com/auth/firebase.messaging";
        googleCredential = GoogleCredential.fromStream(firebaseLocator.getServiceAccountStream())
                .createScoped(Collections.singletonList(messagingScope));
        GoogleCredentials googleCredentials = GoogleCredentials.fromStream(firebaseLocator.getServiceAccountStream());

        projectId = ((ServiceAccountCredentials) googleCredentials).getProjectId();

        if (projectId == null)
            throw new RuntimeException("Project ID must not be null");

        FirebaseOptions options = new FirebaseOptions.Builder()
                .setCredentials(googleCredentials)
                .setDatabaseUrl(getDatabaseUrl())
                .setStorageBucket(getStorageBucket())
                .build();

        FirebaseApp.initializeApp(options);
        log.info(ConsoleHelper.green("Firebase Initialized"));
    } catch (IllegalStateException ise) {
        log.info(ConsoleHelper.yellow("Firebase already initialized"));
    } catch (IllegalArgumentException e) {
        uninitialized = true;
        log.error("Firebase couldn't be initialized", e);
    }
}
 
Example 9
Source File: CloudSpannerConnection.java    From spanner-jdbc with MIT License 5 votes vote down vote up
public static GoogleCredentials getCredentialsFromFile(String credentialsPath)
    throws IOException {
  if (credentialsPath == null || credentialsPath.length() == 0)
    throw new IllegalArgumentException("credentialsPath may not be null or empty");
  GoogleCredentials credentials = null;
  if (credentialsPath.startsWith(GOOGLE_CLOUD_STORAGE_PREFIX)) {
    try {
      Storage storage = StorageOptions.newBuilder().build().getService();
      String bucketName = getBucket(credentialsPath);
      String blobName = getBlob(credentialsPath);
      Blob blob = storage.get(bucketName, blobName);
      ReadChannel reader = blob.reader();
      InputStream inputStream = Channels.newInputStream(reader);
      credentials =
          GoogleCredentials.fromStream(inputStream, CloudSpannerOAuthUtil.HTTP_TRANSPORT_FACTORY);
    } catch (Exception e) {
      throw new IllegalArgumentException(
          "Invalid credentials path: " + credentialsPath + ". Reason: " + e.getMessage(), e);
    }
  } else {
    File credentialsFile = new File(credentialsPath);
    if (!credentialsFile.isFile()) {
      throw new IOException(String.format("Error reading credential file %s: File does not exist",
          credentialsPath));
    }
    try (InputStream credentialsStream = new FileInputStream(credentialsFile)) {
      credentials = GoogleCredentials.fromStream(credentialsStream,
          CloudSpannerOAuthUtil.HTTP_TRANSPORT_FACTORY);
    }
  }
  return credentials;
}
 
Example 10
Source File: FirestoreDataSink.java    From daq with Apache License 2.0 5 votes vote down vote up
private Credentials getProjectCredentials() throws IOException {
  File credentialFile = new File(System.getenv(ServiceOptions.CREDENTIAL_ENV_NAME));
  if (!credentialFile.exists()) {
    throw new RuntimeException(String.format(CREDENTIAL_ERROR_FORMAT,
        credentialFile.getAbsolutePath(), ServiceOptions.CREDENTIAL_ENV_NAME));
  }
  try (FileInputStream serviceAccount = new FileInputStream(credentialFile)) {
    return GoogleCredentials.fromStream(serviceAccount);
  }
}
 
Example 11
Source File: GoogleIdTokenAuthTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@Test
public void testServiceAccountCredentials() throws IOException, GeneralSecurityException {
  Assume.assumeNotNull(credentials);
  final GoogleCredentials serviceAccountCredentials;
  final URI keyUri = URI.create("gs://styx-oss-test/styx-test-user.json");
  try (InputStream is = Files.newInputStream(Paths.get(keyUri))) {
    serviceAccountCredentials = GoogleCredentials.fromStream(is);
  }
  assertThat(canAcquireIdToken(serviceAccountCredentials), is(true));
}
 
Example 12
Source File: GoogleRpcContext.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
/**
 * Read in the JSON file downloaded from the Google Service Account Token Creator
 */
private void setupCredentials(GoogleConfig config) throws IOException {
   Resource resource = Resources.getResource(config.getgRpcKeyFile());

   if (resource.exists()) {
      try (InputStream is = resource.open()) {
         this.creds = GoogleCredentials.fromStream(is);
      }
   }
   else {
      throw new IllegalStateException(MessageFormat.format("Report State has enabled=[{0}], but the gRPC Key File used for authentication does not exist. [{1}]", config.isReportStateEnabled(), config.getgRpcKeyFile()));
   }
}
 
Example 13
Source File: GoogleCredentialsBuilder.java    From aiven-kafka-connect-gcs with GNU Affero General Public License v3.0 5 votes vote down vote up
private static GoogleCredentials getCredentialsFromPath(final String credentialsPath) throws IOException {
    try (final InputStream stream = new FileInputStream(credentialsPath)) {
        return GoogleCredentials.fromStream(stream);
    } catch (final IOException e) {
        throw new IOException("Failed to read GCS credentials from " + credentialsPath, e);
    }
}
 
Example 14
Source File: BigQueryCredentialsSupplier.java    From presto with Apache License 2.0 5 votes vote down vote up
private static Credentials createCredentialsFromFile(String file)
{
    try {
        return GoogleCredentials.fromStream(new FileInputStream(file));
    }
    catch (IOException e) {
        throw new UncheckedIOException("Failed to create Credentials from file", e);
    }
}
 
Example 15
Source File: BigQueryCredentialsSupplier.java    From presto with Apache License 2.0 5 votes vote down vote up
private static Credentials createCredentialsFromKey(String key)
{
    try {
        return GoogleCredentials.fromStream(new ByteArrayInputStream(Base64.decodeBase64(key)));
    }
    catch (IOException e) {
        throw new UncheckedIOException("Failed to create Credentials from key", e);
    }
}
 
Example 16
Source File: AbstractServiceAccountCredentialsStrategy.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
@Override
public GoogleCredentials getGoogleCredentials(Map<PropertyDescriptor, String> properties) throws IOException {
    return GoogleCredentials.fromStream(getServiceAccountJson(properties));
}
 
Example 17
Source File: OldGCSNotebookRepo.java    From zeppelin with Apache License 2.0 4 votes vote down vote up
@Override
public void init(ZeppelinConfiguration zConf) throws IOException {
  this.encoding =  zConf.getString(ConfVars.ZEPPELIN_ENCODING);

  String gcsStorageDir = zConf.getGCSStorageDir();
  if (gcsStorageDir.isEmpty()) {
    throw new IOException("GCS storage directory must be set using 'zeppelin.notebook.gcs.dir'");
  }
  if (!gcsStorageDir.startsWith("gs://")) {
    throw new IOException(String.format(
        "GCS storage directory '%s' must start with 'gs://'.", gcsStorageDir));
  }
  String storageDirWithoutScheme = gcsStorageDir.substring("gs://".length());

  // pathComponents excludes empty string if trailing slash is present
  List<String> pathComponents = Arrays.asList(storageDirWithoutScheme.split("/"));
  if (pathComponents.size() < 1) {
    throw new IOException(String.format(
        "GCS storage directory '%s' must be in the form gs://bucketname/path/to/dir",
        gcsStorageDir));
  }
  this.bucketName = pathComponents.get(0);
  if (pathComponents.size() > 1) {
    this.basePath = Optional.of(StringUtils.join(
        pathComponents.subList(1, pathComponents.size()), "/"));
  } else {
    this.basePath = Optional.absent();
  }

  // Notes are stored at gs://bucketName/basePath/<note-id>/note.json
  if (basePath.isPresent()) {
    this.noteNamePattern = Pattern.compile(
        "^" + Pattern.quote(basePath.get() + "/") + "([^/]+)/note\\.json$");
  } else {
    this.noteNamePattern = Pattern.compile("^([^/]+)/note\\.json$");
  }


  Credentials credentials = GoogleCredentials.getApplicationDefault();
  String credentialJsonPath = zConf.getString(ConfVars.ZEPPELIN_NOTEBOOK_GCS_CREDENTIALS_FILE);
  if (credentialJsonPath != null) {
    credentials = GoogleCredentials.fromStream(new FileInputStream(credentialJsonPath));
  }
  this.storage = StorageOptions.newBuilder().setCredentials(credentials).build().getService();
}
 
Example 18
Source File: GCSNotebookRepo.java    From zeppelin with Apache License 2.0 4 votes vote down vote up
@Override
public void init(ZeppelinConfiguration zConf) throws IOException {
  this.encoding =  zConf.getString(ConfVars.ZEPPELIN_ENCODING);

  String gcsStorageDir = zConf.getGCSStorageDir();
  if (gcsStorageDir.isEmpty()) {
    throw new IOException("GCS storage directory must be set using 'zeppelin.notebook.gcs.dir'");
  }
  if (!gcsStorageDir.startsWith("gs://")) {
    throw new IOException(String.format(
        "GCS storage directory '%s' must start with 'gs://'.", gcsStorageDir));
  }
  String storageDirWithoutScheme = gcsStorageDir.substring("gs://".length());

  // pathComponents excludes empty string if trailing slash is present
  List<String> pathComponents = Arrays.asList(storageDirWithoutScheme.split("/"));
  if (pathComponents.size() < 1) {
    throw new IOException(String.format(
        "GCS storage directory '%s' must be in the form gs://bucketname/path/to/dir",
        gcsStorageDir));
  }
  this.bucketName = pathComponents.get(0);
  if (pathComponents.size() > 1) {
    this.basePath = Optional.of(StringUtils.join(
        pathComponents.subList(1, pathComponents.size()), "/"));
  } else {
    this.basePath = Optional.absent();
  }

  // Notes are stored at gs://bucketName/basePath/<note-id>/note.json
  if (basePath.isPresent()) {
    this.notePathPattern = Pattern.compile(
        "^" + Pattern.quote(basePath.get() + "/") + "(.+\\.zpln)$");
  } else {
    this.notePathPattern = Pattern.compile("^(.+\\.zpln)$");
  }

  Credentials credentials = GoogleCredentials.getApplicationDefault();
  String credentialJsonPath = zConf.getString(ConfVars.ZEPPELIN_NOTEBOOK_GCS_CREDENTIALS_FILE);
  if (credentialJsonPath != null) {
    credentials = GoogleCredentials.fromStream(new FileInputStream(credentialJsonPath));
  }
  this.storage = StorageOptions.newBuilder().setCredentials(credentials).build().getService();
}
 
Example 19
Source File: ConnectorCredentialsProvider.java    From pubsub with Apache License 2.0 4 votes vote down vote up
public void loadJson(String credentialsJson) throws IOException {
  ByteArrayInputStream bs = new ByteArrayInputStream(credentialsJson.getBytes());
  this.credentials = credentials = GoogleCredentials.fromStream(bs);
}
 
Example 20
Source File: ContainerRegistryAuthSupplier.java    From docker-client with Apache License 2.0 2 votes vote down vote up
/**
 * Constructs a ContainerRegistryAuthSupplier for the account with the given credentials.
 *
 * @see Builder
 */
public static Builder fromStream(final InputStream credentialsStream) throws IOException {
  final GoogleCredentials credentials = GoogleCredentials.fromStream(credentialsStream);
  return new Builder(credentials);
}