com.google.api.client.googleapis.auth.oauth2.GoogleCredential Java Examples

The following examples show how to use com.google.api.client.googleapis.auth.oauth2.GoogleCredential. 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: LocalFileCredentialFactory.java    From connector-sdk with Apache License 2.0 8 votes vote down vote up
GoogleCredential getJsonCredential(
    Path keyPath,
    HttpTransport transport,
    JsonFactory jsonFactory,
    HttpRequestInitializer httpRequestInitializer,
    Collection<String> scopes)
    throws IOException {
  try (InputStream is = newInputStream(keyPath)) {
    GoogleCredential credential =
        GoogleCredential.fromStream(is, transport, jsonFactory).createScoped(scopes);
    return new GoogleCredential.Builder()
        .setServiceAccountId(credential.getServiceAccountId())
        .setServiceAccountScopes(scopes)
        .setServiceAccountPrivateKey(credential.getServiceAccountPrivateKey())
        .setTransport(transport)
        .setJsonFactory(jsonFactory)
        .setRequestInitializer(httpRequestInitializer)
        .build();
  }
}
 
Example #2
Source File: ClientAuthenticationFactory.java    From spring-cloud-vault with Apache License 2.0 6 votes vote down vote up
private GoogleCredential getGoogleCredential(GcpIamProperties gcp)
		throws IOException {

	GcpCredentials credentialProperties = gcp.getCredentials();
	if (credentialProperties.getLocation() != null) {
		return GoogleCredential
				.fromStream(credentialProperties.getLocation().getInputStream());
	}

	if (StringUtils.hasText(credentialProperties.getEncodedKey())) {
		return GoogleCredential.fromStream(new ByteArrayInputStream(
				Base64.getDecoder().decode(credentialProperties.getEncodedKey())));
	}

	return GoogleCredential.getApplicationDefault();
}
 
Example #3
Source File: AdHocReportDownloadHelperTest.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  MockitoAnnotations.initMocks(this);

  Enum<?> downloadFormat = TestDownloadFormat.CSV;
  Mockito.<Enum<?>>when(reportRequest.getDownloadFormat()).thenReturn(downloadFormat);

  credential = new GoogleCredential.Builder().setTransport(new NetHttpTransport())
      .setJsonFactory(new JacksonFactory()).build();
  credential.setAccessToken("TEST_ACCESS_TOKEN");

  AdWordsSession session = new AdWordsSession.Builder()
      .withUserAgent("TEST_APP")
      .withOAuth2Credential(credential)
      .withEndpoint(testHttpServer.getServerUrl())
      .withDeveloperToken("TEST_DEVELOPER_TOKEN")
      .withClientCustomerId("TEST_CLIENT_CUSTOMER_ID")
      .build();

  helper =
      new GenericAdWordsServices()
          .getBootstrapper()
          .getInstanceOf(session, AdHocReportDownloadHelper.class);
  exceptionBuilder = DetailedReportDownloadResponseException::new;
}
 
Example #4
Source File: DatastoreTest.java    From async-datastore-client with Apache License 2.0 6 votes vote down vote up
private DatastoreConfig datastoreConfig() {
  final DatastoreConfig.Builder config = DatastoreConfig.builder()
      .connectTimeout(5000)
      .requestTimeout(1000)
      .maxConnections(5)
      .requestRetry(3)
      .version(VERSION)
      .host(DATASTORE_HOST)
      .project(PROJECT);

  if (NAMESPACE != null) {
    config.namespace(NAMESPACE);
  }

  if (KEY_PATH != null) {
    try {
      FileInputStream creds = new FileInputStream(new File(KEY_PATH));
      config.credential(GoogleCredential.fromStream(creds).createScoped(DatastoreConfig.SCOPES));
    }  catch (final IOException e) {
      System.err.println("Failed to load credentials " + e.getMessage());
      System.exit(1);
    }
  }

  return config.build();
}
 
Example #5
Source File: MlEngineModel.java    From zoltar with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a Google Cloud ML Engine backed model.
 *
 * @param id {@link Model.Id} needs to be created with the following format:
 *     <pre>"projects/{PROJECT_ID}/models/{MODEL_ID}"</pre>
 *     or
 *     <pre>"projects/{PROJECT_ID}/models/{MODEL_ID}/versions/{MODEL_VERSION}"</pre>
 */
public static MlEngineModel create(final Model.Id id)
    throws IOException, GeneralSecurityException {
  final HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
  final JsonFactory jsonFactory = Utils.getDefaultJsonFactory();
  final GoogleCredential credential =
      GoogleCredential.getApplicationDefault()
          .createScoped(CloudMachineLearningEngineScopes.all());

  final CloudMachineLearningEngine mlEngine =
      new CloudMachineLearningEngine.Builder(httpTransport, jsonFactory, credential)
          .setApplicationName(APPLICATION_NAME)
          .build();

  return new AutoValue_MlEngineModel(id, mlEngine, httpTransport);
}
 
Example #6
Source File: DatastoreHelper.java    From google-cloud-datastore with Apache License 2.0 6 votes vote down vote up
private static Credential getCredentialFromEnv() throws GeneralSecurityException, IOException {
  if (System.getenv(LOCAL_HOST_ENV_VAR) != null) {
    logger.log(Level.INFO, "{0} environment variable was set. Not using credentials.",
        new Object[] {LOCAL_HOST_ENV_VAR});
    return null;
  }
  String serviceAccount = System.getenv(SERVICE_ACCOUNT_ENV_VAR);
  String privateKeyFile = System.getenv(PRIVATE_KEY_FILE_ENV_VAR);
  if (serviceAccount != null && privateKeyFile != null) {
    logger.log(Level.INFO, "{0} and {1} environment variables were set. "
        + "Using service account credential.",
        new Object[] {SERVICE_ACCOUNT_ENV_VAR, PRIVATE_KEY_FILE_ENV_VAR});
    return getServiceAccountCredential(serviceAccount, privateKeyFile);
  }
  return GoogleCredential.getApplicationDefault()
      .createScoped(DatastoreOptions.SCOPES);
}
 
Example #7
Source File: GcpIamClientAuthenticationProvider.java    From spring-cloud-config with Apache License 2.0 6 votes vote down vote up
public static GcpCredentialSupplier getGoogleCredential(
		VaultEnvironmentProperties.GcpIamProperties gcp) {
	return () -> {

		VaultEnvironmentProperties.GcpCredentials credentialProperties = gcp
				.getCredentials();
		if (credentialProperties.getLocation() != null) {
			return GoogleCredential.fromStream(
					credentialProperties.getLocation().getInputStream());
		}

		if (StringUtils.hasText(credentialProperties.getEncodedKey())) {
			return GoogleCredential.fromStream(new ByteArrayInputStream(Base64
					.getDecoder().decode(credentialProperties.getEncodedKey())));
		}

		return GoogleCredential.getApplicationDefault();
	};
}
 
Example #8
Source File: CredentialStore.java    From jdrivesync with Apache License 2.0 6 votes vote down vote up
public Optional<Credential> load() {
     Properties properties = new Properties();
     try {
File file = getAuthenticationFile(options);
         if(!file.exists() || !file.canRead()) {
             LOGGER.log(Level.FINE, "Cannot find or read properties file. Returning empty credentials.");
             return Optional.empty();
         }
         properties.load(new FileReader(file));
         HttpTransport httpTransport = new NetHttpTransport();
         JsonFactory jsonFactory = new JacksonFactory();
         GoogleCredential credential = new GoogleCredential.Builder().setJsonFactory(jsonFactory)
                 .setTransport(httpTransport).setClientSecrets(OAuth2ClientCredentials.CLIENT_ID, OAuth2ClientCredentials.CLIENT_SECRET).build();
         credential.setAccessToken(properties.getProperty(PROP_ACCESS_TOKEN));
         credential.setRefreshToken(properties.getProperty(PROP_REFRESH_TOKEN));
         return Optional.of(credential);
     } catch (IOException e) {
         throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to load properties file: " + e.getMessage(), e);
     }
 }
 
Example #9
Source File: FirebaseOptionsTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void createOptionsWithOnlyMandatoryValuesSet() throws IOException {
  FirebaseOptions firebaseOptions =
      new FirebaseOptions.Builder()
          .setCredentials(GoogleCredentials.fromStream(ServiceAccount.EDITOR.asStream()))
          .build();
  assertNotNull(firebaseOptions.getJsonFactory());
  assertNotNull(firebaseOptions.getHttpTransport());
  assertNotNull(firebaseOptions.getThreadManager());
  assertNull(firebaseOptions.getDatabaseUrl());
  assertNull(firebaseOptions.getStorageBucket());
  assertEquals(0, firebaseOptions.getConnectTimeout());
  assertEquals(0, firebaseOptions.getReadTimeout());

  GoogleCredentials credentials = firebaseOptions.getCredentials();
  assertNotNull(credentials);
  assertTrue(credentials instanceof ServiceAccountCredentials);
  assertEquals(
      GoogleCredential.fromStream(ServiceAccount.EDITOR.asStream()).getServiceAccountId(),
      ((ServiceAccountCredentials) credentials).getClientEmail());
  assertNull(firebaseOptions.getFirestoreOptions());
}
 
Example #10
Source File: GoogleSpreadsheet.java    From pdi-google-spreadsheet-plugin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static String getAccessToken(String email, KeyStore pks) throws Exception {
    PrivateKey pk = getPrivateKey(pks);
    if (pk != null && !email.equals("")) {
        try {
            GoogleCredential credential = new GoogleCredential.Builder().setTransport(GoogleSpreadsheet.HTTP_TRANSPORT)
                    .setJsonFactory(GoogleSpreadsheet.JSON_FACTORY).setServiceAccountScopes(GoogleSpreadsheet.SCOPES).setServiceAccountId(email)
                    .setServiceAccountPrivateKey(pk).build();

            HttpRequestFactory requestFactory = GoogleSpreadsheet.HTTP_TRANSPORT.createRequestFactory(credential);
            GenericUrl url = new GenericUrl(GoogleSpreadsheet.getSpreadsheetFeedURL().toString());
            HttpRequest request = requestFactory.buildGetRequest(url);
            request.execute();
            return credential.getAccessToken();
        } catch (Exception e) {
            throw new Exception("Error fetching Access Token", e);
        }
    }
    return null;
}
 
Example #11
Source File: GuiMain.java    From google-sites-liberation with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve OAuth 2.0 credentials.
 * 
 * @return OAuth 2.0 Credential instance.
 * @throws IOException
 */
private Credential getCredentials() throws IOException {
  String code = tokenField.getText();
  HttpTransport transport = new NetHttpTransport();
  JacksonFactory jsonFactory = new JacksonFactory();
  String CLIENT_SECRET = "EPME5fbwiNLCcMsnj3jVoXeY";

  // Step 2: Exchange -->
  GoogleTokenResponse response = new GoogleAuthorizationCodeTokenRequest(
      transport, jsonFactory, CLIENT_ID, CLIENT_SECRET, code,
      REDIRECT_URI).execute();
  // End of Step 2 <--

  // Build a new GoogleCredential instance and return it.
  return new GoogleCredential.Builder()
      .setClientSecrets(CLIENT_ID, CLIENT_SECRET)
      .setJsonFactory(jsonFactory).setTransport(transport).build()
      .setAccessToken(response.getAccessToken())
      .setRefreshToken(response.getRefreshToken());
}
 
Example #12
Source File: GCPServiceAccount.java    From policyscanner with Apache License 2.0 6 votes vote down vote up
/**
 * Get the API stub for accessing the IAM Service Accounts API.
 * @return ServiceAccounts api stub for accessing the IAM Service Accounts API.
 * @throws IOException Thrown if there's an IO error initializing the api connection.
 * @throws GeneralSecurityException Thrown if there's a security error
 * initializing the connection.
 */
public static ServiceAccounts getServiceAccountsApiStub() throws IOException, GeneralSecurityException {
  if (serviceAccountsApiStub == null) {
    HttpTransport transport;
    GoogleCredential credential;
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    transport = GoogleNetHttpTransport.newTrustedTransport();
    credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
    if (credential.createScopedRequired()) {
      Collection<String> scopes = IamScopes.all();
      credential = credential.createScoped(scopes);
    }
    serviceAccountsApiStub = new Iam.Builder(transport, jsonFactory, credential)
        .build()
        .projects()
        .serviceAccounts();
  }
  return serviceAccountsApiStub;
}
 
Example #13
Source File: DatastoreFactoryTest.java    From google-cloud-datastore with Apache License 2.0 6 votes vote down vote up
/**
 * Specifying both credential and transport, the factory will use the
 * transport specified and not the one in the credential.
 */
@Test
public void makeClient_WithCredentialTransport() {
  NetHttpTransport credTransport = new NetHttpTransport();
  NetHttpTransport transport = new NetHttpTransport();
  GoogleCredential credential = new GoogleCredential.Builder()
      .setTransport(credTransport)
      .build();
  DatastoreOptions options = new DatastoreOptions.Builder()
      .projectId(PROJECT_ID)
      .credential(credential)
      .transport(transport)
      .build();
  HttpRequestFactory f = factory.makeClient(options);
  assertNotSame(credTransport, f.getTransport());
  assertEquals(transport, f.getTransport());
}
 
Example #14
Source File: PubsubUtils.java    From cloud-pubsub-samples-java with Apache License 2.0 6 votes vote down vote up
/**
 * Builds a new Pubsub client and returns it.
 *
 * @param httpTransport HttpTransport for Pubsub client.
 * @param jsonFactory JsonFactory for Pubsub client.
 * @return Pubsub client.
 * @throws IOException when we can not get the default credentials.
 */
public static Pubsub getClient(final HttpTransport httpTransport,
                               final JsonFactory jsonFactory)
         throws IOException {
    Preconditions.checkNotNull(httpTransport);
    Preconditions.checkNotNull(jsonFactory);
    GoogleCredential credential =
        GoogleCredential.getApplicationDefault(httpTransport, jsonFactory);
    if (credential.createScopedRequired()) {
        credential = credential.createScoped(PubsubScopes.all());
    }
    // Please use custom HttpRequestInitializer for automatic
    // retry upon failures.
    HttpRequestInitializer initializer =
        new RetryHttpInitializerWrapper(credential);
    return new Pubsub.Builder(httpTransport, jsonFactory, initializer)
            .setApplicationName(APP_NAME)
            .build();
}
 
Example #15
Source File: PubSubWrapper.java    From eip with MIT License 6 votes vote down vote up
/**
     * Setup authorization for local app based on private key.
     * See <a href="https://cloud.google.com/pubsub/configure">cloud.google.com/pubsub/configure</a>
     */
    private void createClient(String private_key_file, String email) throws IOException, GeneralSecurityException {
        HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
        GoogleCredential credential = new GoogleCredential.Builder()
                .setTransport(transport)
                .setJsonFactory(JSON_FACTORY)
                .setServiceAccountScopes(PubsubScopes.all())
                .setServiceAccountId(email)
                .setServiceAccountPrivateKeyFromP12File(new File(private_key_file))
                .build();
        // Please use custom HttpRequestInitializer for automatic retry upon failures.
//        HttpRequestInitializer initializer = new RetryHttpInitializerWrapper(credential);
        pubsub = new Pubsub.Builder(transport, JSON_FACTORY, credential)
                .setApplicationName("eaipubsub")
                .build();
    }
 
Example #16
Source File: GSpreadFeedProcessor.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * helper method to refresh the access token and authenticate
 *
 * @throws Exception
 */
private void refreshAndAuthenticate() throws Exception {
    GoogleCredential credential = getBaseCredential();
    credential.setAccessToken(this.accessToken);
    credential.setRefreshToken(this.refreshToken);
    credential.refreshToken();
    this.accessToken = credential.getAccessToken();
    this.service.setOAuth2Credentials(credential);
}
 
Example #17
Source File: BatchingIndexingServiceImpl.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
public static BatchingIndexingService fromConfiguration(
    CloudSearch service, GoogleCredential credential) {
  checkState(Configuration.isInitialized(), "config not initialized");
  return new Builder()
      .setService(service)
      .setBatchPolicy(BatchPolicy.fromConfiguration())
      .setCredential(credential)
      .build();
}
 
Example #18
Source File: Uploader.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
public Uploader build() throws IOException, GeneralSecurityException {
  if (credentialFactory == null) {
    credentialFactory = uploaderHelper.createCredentialFactory(serviceAccountKeyFilePath);
  }

  if (transport == null) {
    transport = uploaderHelper.createTransport();
  }

  GoogleCredential credential = credentialFactory.getCredential(API_SCOPES);
  CloudSearch.Builder serviceBuilder =
      new CloudSearch.Builder(
          transport,
          JSON_FACTORY,
          credential);

  if (!Strings.isNullOrEmpty(rootUrl)) {
    serviceBuilder.setRootUrl(rootUrl);
  }
  cloudSearch = serviceBuilder.setApplicationName(this.getClass().getName()).build();

  contentUploadService =
      new ContentUploadServiceImpl.Builder()
          .setCredentialFactory(credentialFactory)
          .setRequestInitializer(requestInitializer)
          .setRootUrl(rootUrl)
          .setRequestTimeout(connectTimeoutSeconds, readTimeoutSeconds)
          .build();
  return new Uploader(this);
}
 
Example #19
Source File: QuickstartApiConnector.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Builds and return an authorized CloudSearch client service.
 *
 * @param keyFile the service account key file name
 * @return an authorized CloudSearch client service
 */
private static CloudSearch getCloudSearchService(String keyFile, String rootUrl)
    throws IOException, GeneralSecurityException {
  InputStream in = Files.newInputStream(Paths.get(keyFile));
  httpTransport = GoogleNetHttpTransport.newTrustedTransport();
  Credential credential =
      GoogleCredential.fromStream(in, httpTransport, JSON_FACTORY).createScoped(API_SCOPES);
  return new CloudSearch.Builder(httpTransport, JSON_FACTORY, credential)
      .setApplicationName(APPLICATION_NAME)
      .setRootUrl(rootUrl)
      .build();
}
 
Example #20
Source File: Snippets.java    From java-samples with Apache License 2.0 5 votes vote down vote up
public BatchUpdatePresentationResponse createImage(String presentationId,
                                                   String slideId,
                                                   GoogleCredential credential)
        throws IOException {
    Slides slidesService = this.service;
    // [START slides_create_image]
    String imageUrl = "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png";

    // Create a new image, using the supplied object ID, with content downloaded from imageUrl.
    List<Request> requests = new ArrayList<>();
    String imageId = "MyImageId_01";
    Dimension emu4M = new Dimension().setMagnitude(4000000.0).setUnit("EMU");
    requests.add(new Request()
            .setCreateImage(new CreateImageRequest()
                    .setObjectId(imageId)
                    .setUrl(imageUrl)
                    .setElementProperties(new PageElementProperties()
                            .setPageObjectId(slideId)
                            .setSize(new Size()
                                    .setHeight(emu4M)
                                    .setWidth(emu4M))
                            .setTransform(new AffineTransform()
                                    .setScaleX(1.0)
                                    .setScaleY(1.0)
                                    .setTranslateX(100000.0)
                                    .setTranslateY(100000.0)
                                    .setUnit("EMU")))));

    // Execute the request.
    BatchUpdatePresentationRequest body =
            new BatchUpdatePresentationRequest().setRequests(requests);
    BatchUpdatePresentationResponse response =
            slidesService.presentations().batchUpdate(presentationId, body).execute();
    CreateImageResponse createImageResponse = response.getReplies().get(0).getCreateImage();
    System.out.println("Created image with ID: " + createImageResponse.getObjectId());
    // [END slides_create_image]
    return response;
}
 
Example #21
Source File: BaragonServiceModule.java    From Baragon with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
@Named(GOOGLE_CLOUD_COMPUTE_SERVICE)
public Optional<Compute> provideComputeService(BaragonConfiguration config) throws Exception {
  if (!config.getGoogleCloudConfiguration().isEnabled()) {
    return Optional.absent();
  }
  HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();

  GoogleCredential credential = null;

  if (config.getGoogleCloudConfiguration().getGoogleCredentialsFile() != null) {
    File credentialsFile = new File(config.getGoogleCloudConfiguration().getGoogleCredentialsFile());
    credential = GoogleCredential.fromStream(
        new FileInputStream(credentialsFile)
    );
  } else if (config.getGoogleCloudConfiguration().getGoogleCredentials() != null) {
    credential = GoogleCredential.fromStream(
        new ByteArrayInputStream(config.getGoogleCloudConfiguration().getGoogleCredentials().getBytes("UTF-8"))
    );
  } else {
    throw new RuntimeException("Must specify googleCloudCredentials or googleCloudCredentialsFile when using google cloud api");
  }

  if (credential.createScopedRequired()) {
    credential =
        credential.createScoped(Collections.singletonList("https://www.googleapis.com/auth/cloud-platform"));
  }

  return Optional.of(new Compute.Builder(httpTransport, jsonFactory, credential)
      .setApplicationName("BaragonService")
      .build());
}
 
Example #22
Source File: BaseApiService.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
protected GoogleCredential setupServiceAndCredentials()
    throws GeneralSecurityException, IOException {
  checkArgument(credentialFactory != null, "Credential Factory cannot be null.");
  GoogleCredential credential = credentialFactory.getCredential(getApiScopes());
  if (this.service == null) {
    if (jsonFactory == null) {
      jsonFactory = JacksonFactory.getDefaultInstance();
    }

    if (transport == null) {
      transport = googleProxy.getHttpTransport();
    }

    if (requestInitializer == null) {
      requestInitializer =
          new RetryRequestInitializer(
              checkNotNull(retryPolicy, "retry policy can not be null"));
    }

    AbstractGoogleJsonClient.Builder serviceBuilder =
        getServiceBuilder(
            transport,
            jsonFactory,
            chainedHttpRequestInitializer(
                credential,
                requestInitializer,
                requestTimeoutInitializer,
                googleProxy.getHttpRequestInitializer()));

    if (!Strings.isNullOrEmpty(rootUrl)) {
      serviceBuilder.setRootUrl(rootUrl);
    }
    service = (T) serviceBuilder.setApplicationName(this.getClass().getName()).build();
  }
  return credential;
}
 
Example #23
Source File: GetRefreshToken.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
private static Credential getOAuth2Credential(GoogleClientSecrets clientSecrets)
    throws IOException {
  GoogleAuthorizationCodeFlow authorizationFlow = new GoogleAuthorizationCodeFlow.Builder(
      new NetHttpTransport(),
      new JacksonFactory(),
      clientSecrets,
      SCOPES)
      // Set the access type to offline so that the token can be refreshed.
      // By default, the library will automatically refresh tokens when it
      // can, but this can be turned off by setting
      // api.adwords.refreshOAuth2Token=false in your ads.properties file.
      .setAccessType("offline").build();

  String authorizeUrl =
      authorizationFlow.newAuthorizationUrl().setRedirectUri(CALLBACK_URL).build();
  System.out.printf("Paste this url in your browser:%n%s%n", authorizeUrl);

  // Wait for the authorization code.
  System.out.println("Type the code you received here: ");
  @SuppressWarnings("DefaultCharset") // Reading from stdin, so default charset is appropriate.
  String authorizationCode = new BufferedReader(new InputStreamReader(System.in)).readLine();

  // Authorize the OAuth2 token.
  GoogleAuthorizationCodeTokenRequest tokenRequest =
      authorizationFlow.newTokenRequest(authorizationCode);
  tokenRequest.setRedirectUri(CALLBACK_URL);
  GoogleTokenResponse tokenResponse = tokenRequest.execute();

  // Create the OAuth2 credential.
  GoogleCredential credential = new GoogleCredential.Builder()
      .setTransport(new NetHttpTransport())
      .setJsonFactory(new JacksonFactory())
      .setClientSecrets(clientSecrets)
      .build();

  // Set authorized credentials.
  credential.setFromTokenResponse(tokenResponse);

  return credential;
}
 
Example #24
Source File: CredentialFactory.java    From hadoop-connectors with Apache License 2.0 5 votes vote down vote up
private Credential getCredentialsFromSAParameters(List<String> scopes, HttpTransport transport)
    throws IOException {
  logger.atFine().log("getCredentialsFromSAParameters(%s, %s)", scopes, transport);
  GoogleCredential.Builder builder =
      new GoogleCredential.Builder()
          .setTransport(transport)
          .setJsonFactory(JSON_FACTORY)
          .setServiceAccountId(options.getServiceAccountEmail())
          .setServiceAccountScopes(scopes)
          .setServiceAccountPrivateKey(
              privateKeyFromPkcs8(options.getServiceAccountPrivateKey().value()))
          .setServiceAccountPrivateKeyId(options.getServiceAccountPrivateKeyId().value());
  return new GoogleCredentialWithRetry(builder, options.getTokenServerUrl());
}
 
Example #25
Source File: AdWordsJaxWsSoapTimeoutIntegrationTest.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Tests that the request timeout in ads.properties is enforced.
 */
@Test
public void testRequestTimeoutEnforced() throws Exception {
  testHttpServer.setMockResponseBody(SoapResponseXmlProvider.getTestSoapResponse(API_VERSION));
  testHttpServer.setDelay(200L);
  
  GoogleCredential credential = new GoogleCredential.Builder().setTransport(
      new NetHttpTransport()).setJsonFactory(new JacksonFactory()).build();
  credential.setAccessToken("TEST_ACCESS_TOKEN");

  AdWordsSession session = new AdWordsSession.Builder()
      .withUserAgent("TEST_APP")
      .withOAuth2Credential(credential)
      .withEndpoint(testHttpServer.getServerUrl())
      .withDeveloperToken("TEST_DEVELOPER_TOKEN")
      .withClientCustomerId("TEST_CLIENT_CUSTOMER_ID")
      .build();

  BudgetServiceInterface budgetService =
      new AdWordsServices().get(session, BudgetServiceInterface.class);
  
  Budget budget = new Budget();
  budget.setName("Test Budget Name");
  Money money = new Money();
  money.setMicroAmount(50000000L);
  budget.setAmount(money);
  budget.setDeliveryMethod(BudgetBudgetDeliveryMethod.STANDARD);

  BudgetOperation operation = new BudgetOperation();
  operation.setOperand(budget);
  operation.setOperator(Operator.ADD);
  
  thrown.expect(WebServiceException.class);
  thrown.expectMessage("Read timed out");
  budgetService.mutate(Lists.newArrayList(operation));
}
 
Example #26
Source File: CredentialFactory.java    From hadoop-connectors with Apache License 2.0 5 votes vote down vote up
/**
 * Get credentials listed in a JSON file.
 *
 * @param scopes The OAuth scopes that the credential should be valid for.
 * @param transport The HttpTransport used for authorization
 */
private Credential getCredentialFromJsonKeyFile(List<String> scopes, HttpTransport transport)
    throws IOException {
  logger.atFine().log(
      "getCredentialFromJsonKeyFile(%s, %s) from '%s'",
      scopes, transport, options.getServiceAccountJsonKeyFile());

  try (FileInputStream fis = new FileInputStream(options.getServiceAccountJsonKeyFile())) {
    return GoogleCredentialWithRetry.fromGoogleCredential(
        GoogleCredential.fromStream(fis, transport, JSON_FACTORY).createScoped(scopes),
        options.getTokenServerUrl());
  }
}
 
Example #27
Source File: Configure.java    From quickstart-java with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve a valid access token that can be use to authorize requests to the Remote Config REST
 * API.
 *
 * @return Access token.
 * @throws IOException
 */
// [START retrieve_access_token]
private static String getAccessToken() throws IOException {
  GoogleCredential googleCredential = GoogleCredential
      .fromStream(new FileInputStream("service-account.json"))
      .createScoped(Arrays.asList(SCOPES));
  googleCredential.refreshToken();
  return googleCredential.getAccessToken();
}
 
Example #28
Source File: UsersServiceImpl.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
/** Builds an instance of {@link UsersServiceImpl} */
@Override
public UsersServiceImpl build() throws GeneralSecurityException, IOException {
  GoogleCredential credentials = setupServiceAndCredentials();
  if (batchService == null) {
    batchService =
        new BatchRequestService.Builder(service)
            .setBatchPolicy(batchPolicy)
            .setRetryPolicy(retryPolicy)
            .setGoogleCredential(credentials)
            .build();
  }

  return new UsersServiceImpl(this);
}
 
Example #29
Source File: GcpIamAuthenticationOptionsBuilderUnitTests.java    From spring-vault with Apache License 2.0 5 votes vote down vote up
@Test
void shouldAllowServiceAccountIdProviderOverride() {

	GoogleCredential credential = createGoogleCredential();

	GcpIamAuthenticationOptions options = GcpIamAuthenticationOptions.builder().credential(credential)
			.serviceAccountIdAccessor((GoogleCredential googleCredential) -> "[email protected]").role("foo")
			.build();

	assertThat(options.getServiceAccountIdAccessor().getServiceAccountId(credential)).isEqualTo("[email protected]");
}
 
Example #30
Source File: CredentialFromAccessTokenProviderClassFactoryTest.java    From hadoop-connectors with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateCredentialFromAccessTokenProvider() {
  AccessTokenProvider accessTokenProvider = new TestingAccessTokenProvider();
  GoogleCredential credential =
      GoogleCredentialWithAccessTokenProvider.fromAccessTokenProvider(clock, accessTokenProvider);

  assertThat(credential.getAccessToken()).isEqualTo(TestingAccessTokenProvider.FAKE_ACCESS_TOKEN);
  assertThat(credential.getExpirationTimeMilliseconds())
      .isEqualTo(TestingAccessTokenProvider.EXPIRATION_TIME_MILLISECONDS);
}