com.google.auth.oauth2.UserCredentials Java Examples

The following examples show how to use com.google.auth.oauth2.UserCredentials. 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: ContainerRegistryAuthSupplier.java    From docker-client with Apache License 2.0 6 votes vote down vote up
public ContainerRegistryAuthSupplier build() {
  final GoogleCredentials credentials = this.credentials.createScoped(scopes);

  // log some sort of identifier for the credentials, which requires looking at the
  // instance type
  if (credentials instanceof ServiceAccountCredentials) {
    final String clientEmail = ((ServiceAccountCredentials) credentials).getClientEmail();
    log.info("loaded credentials for service account with clientEmail={}", clientEmail);
  } else if (credentials instanceof UserCredentials) {
    final String clientId = ((UserCredentials) credentials).getClientId();
    log.info("loaded credentials for user account with clientId={}", clientId);
  }

  final Clock clock = Clock.systemDefaultZone();
  final DefaultCredentialRefresher refresher = new DefaultCredentialRefresher();

  return new ContainerRegistryAuthSupplier(credentials, clock, minimumExpiryMillis, refresher);
}
 
Example #2
Source File: GcsSinkConfigTest.java    From aiven-kafka-connect-gcs with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
void gcsCredentialsJson() throws IOException {
    final Map<String, String> properties = new HashMap<>();
    properties.put("gcs.bucket.name", "test-bucket");

    final String credentialsJson = Resources.toString(
        getClass().getClassLoader().getResource("test_gcs_credentials.json"),
        StandardCharsets.UTF_8
    );
    properties.put("gcs.credentials.json", credentialsJson);

    final GcsSinkConfig config = new GcsSinkConfig(properties);
    final UserCredentials credentials = (UserCredentials) config.getCredentials();
    assertEquals("test-client-id", credentials.getClientId());
    assertEquals("test-client-secret", credentials.getClientSecret());
}
 
Example #3
Source File: GoogleAdsClientTest.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that the loginCustomerId can be unset when cloning the client via builder methods. This
 * is important so that users can easily change the login customer ID.
 */
@Test
public void setLoginCustomerId_canClearOnceSet() {
  Credentials credentials =
      UserCredentials.newBuilder()
          .setClientId(CLIENT_ID)
          .setClientSecret(CLIENT_SECRET)
          .setRefreshToken(REFRESH_TOKEN)
          .build();
  GoogleAdsClient client =
      GoogleAdsClient.newBuilder()
          .setCredentials(credentials)
          .setDeveloperToken(DEVELOPER_TOKEN)
          .setLoginCustomerId(1L)
          .setEnableGeneratedCatalog(enabledGeneratedCatalog)
          .build();
  client = client.toBuilder().setLoginCustomerId(null).build();
  assertNull("Unable to clear loginCustomerId", client.getLoginCustomerId());
}
 
Example #4
Source File: GoogleAdsClientTest.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
/**
 * Tests building a client without the use of a properties file.
 */
@Test
public void buildWithoutPropertiesFile_supportsAllFields() throws IOException {
  Credentials credentials =
      UserCredentials.newBuilder()
          .setClientId(CLIENT_ID)
          .setClientSecret(CLIENT_SECRET)
          .setRefreshToken(REFRESH_TOKEN)
          .build();
  GoogleAdsClient client =
      GoogleAdsClient.newBuilder()
          .setCredentials(credentials)
          .setDeveloperToken(DEVELOPER_TOKEN)
          .setLoginCustomerId(LOGIN_CUSTOMER_ID)
          .setEnableGeneratedCatalog(enabledGeneratedCatalog)
          .setTransportChannelProvider(localChannelProvider)
          .build();
  assertGoogleAdsClient(client);
}
 
Example #5
Source File: GoogleAdsClientTest.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
/**
 * Verifies that builder supports nullable loginCustomerId.
 */
@Test
public void build_loginCustomerId_allowsNullable() {
  Credentials credentials =
      UserCredentials.newBuilder()
          .setClientId(CLIENT_ID)
          .setClientSecret(CLIENT_SECRET)
          .setRefreshToken(REFRESH_TOKEN)
          .build();
  GoogleAdsClient client =
      GoogleAdsClient.newBuilder()
          .setCredentials(credentials)
          .setDeveloperToken(DEVELOPER_TOKEN)
          .setEnableGeneratedCatalog(enabledGeneratedCatalog)
          .build();
  assertNull("invalid login-customer-id", client.getLoginCustomerId());
}
 
Example #6
Source File: GoogleAdsClientTest.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
/**
 * Verifies that builder does not require enableGeneratedCatalog to be set explicitly.
 */
@Test
public void build_enableGeneratedCatalog_not_required() throws IOException {
  Credentials credentials =
      UserCredentials.newBuilder()
          .setClientId(CLIENT_ID)
          .setClientSecret(CLIENT_SECRET)
          .setRefreshToken(REFRESH_TOKEN)
          .build();
  GoogleAdsClient client =
      GoogleAdsClient.newBuilder()
          .setCredentials(credentials)
          .setDeveloperToken(DEVELOPER_TOKEN)
          .setLoginCustomerId(LOGIN_CUSTOMER_ID)
          .build();
  assertGoogleAdsClient(client, LOGIN_CUSTOMER_ID, false);
}
 
Example #7
Source File: GoogleAdsClientTest.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
/**
 * Asserts that the provided client matches expectations. Expects a login customer ID that matches
 * the provided value.
 */
private void assertGoogleAdsClient(
    GoogleAdsClient client,
    @Nullable Long loginCustomerId,
    boolean enableGeneratedCatalog)
    throws IOException {
  assertNotNull("Null client", client);

  Credentials credentials = client.getCredentials();
  assertNotNull("Null credentials", credentials);
  assertThat(credentials, Matchers.instanceOf(UserCredentials.class));
  UserCredentials userCredentials = (UserCredentials) credentials;
  assertEquals("Client ID", CLIENT_ID, userCredentials.getClientId());
  assertEquals("Client secret", CLIENT_SECRET, userCredentials.getClientSecret());
  assertEquals("Refresh token", REFRESH_TOKEN, userCredentials.getRefreshToken());

  assertEquals("Developer token", DEVELOPER_TOKEN, client.getDeveloperToken());
  assertEquals("Login customer id", loginCustomerId, client.getLoginCustomerId());
  assertEquals(
      "Enable generated catalog",
      enableGeneratedCatalog,
      client.getEnableGeneratedCatalog());
}
 
Example #8
Source File: GoogleIdTokenAuthTest.java    From styx with Apache License 2.0 6 votes vote down vote up
@Test
public void testUserCredentialsWithAccessTokenFails() throws IOException,
                                                             GeneralSecurityException {
  Assume.assumeThat(Objects.requireNonNull(credentials), is(instanceOf(UserCredentials.class)));
  credentials.refresh();
  final GoogleCredentials accessTokenCredentials = GoogleCredentials.newBuilder()
      .setAccessToken(credentials.getAccessToken())
      .build();
  final GoogleIdTokenAuth idTokenAuth = GoogleIdTokenAuth.of(accessTokenCredentials);
  try {
    idTokenAuth.getToken("http://styx.foo.bar");
    fail();
  } catch (IOException e) {
    assertThat(e.getMessage(), startsWith("Principal is not a service account, unable to acquire id token:"));
  }
}
 
Example #9
Source File: PhotosLibraryClientFactory.java    From java-photoslibrary with Apache License 2.0 6 votes vote down vote up
private static Credentials getUserCredentials(String credentialsPath, List<String> selectedScopes)
    throws IOException, GeneralSecurityException {
  GoogleClientSecrets clientSecrets =
      GoogleClientSecrets.load(
          JSON_FACTORY, new InputStreamReader(new FileInputStream(credentialsPath)));
  String clientId = clientSecrets.getDetails().getClientId();
  String clientSecret = clientSecrets.getDetails().getClientSecret();

  GoogleAuthorizationCodeFlow flow =
      new GoogleAuthorizationCodeFlow.Builder(
              GoogleNetHttpTransport.newTrustedTransport(),
              JSON_FACTORY,
              clientSecrets,
              selectedScopes)
          .setDataStoreFactory(new FileDataStoreFactory(DATA_STORE_DIR))
          .setAccessType("offline")
          .build();
  LocalServerReceiver receiver =
      new LocalServerReceiver.Builder().setPort(LOCAL_RECEIVER_PORT).build();
  Credential credential = new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
  return UserCredentials.newBuilder()
      .setClientId(clientId)
      .setClientSecret(clientSecret)
      .setRefreshToken(credential.getRefreshToken())
      .build();
}
 
Example #10
Source File: Credentials.java    From androidthings-googleassistant with Apache License 2.0 5 votes vote down vote up
public static UserCredentials fromResource(Context context, int resourceId)
        throws IOException, JSONException {
    InputStream is = context.getResources().openRawResource(resourceId);
    byte[] bytes = new byte[is.available()];
    is.read(bytes);
    JSONObject json = new JSONObject(new String(bytes, "UTF-8"));
    return new UserCredentials(
            json.getString("client_id"),
            json.getString("client_secret"),
            json.getString("refresh_token")
    );
}
 
Example #11
Source File: GoogleIdTokenAuthTest.java    From styx with Apache License 2.0 5 votes vote down vote up
private static boolean canAcquireIdToken(GoogleCredentials credentials)
    throws IOException, GeneralSecurityException {
  final GoogleIdTokenAuth idTokenAuth = GoogleIdTokenAuth.of(credentials);
  final String targetAudience = "http://styx.foo.bar";
  final Optional<String> token = idTokenAuth.getToken(targetAudience);
  final GoogleIdToken verifiedToken = VERIFIER.verify(token.orElseThrow());
  assertThat(verifiedToken, is(notNullValue()));
  if (!(credentials instanceof UserCredentials)) {
    // TODO: can we procure user id tokens with the styx service audience?
    assertThat(verifiedToken.verifyAudience(ImmutableList.of(targetAudience)), is(true));
  }
  return true;
}
 
Example #12
Source File: GoogleIdTokenAuthTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@Test
public void testMockUserCredentials() throws IOException, GeneralSecurityException, InterruptedException {
  final MockResponse tokenResponse = new MockResponse()
      .setBody(Utils.getDefaultJsonFactory().toString(ImmutableMap.of("id_token", "test-id-token")));
  metadataServer.enqueue(tokenResponse);
  metadataServer.start();

  final AccessToken accessToken = new AccessToken("test-access-token",
      Date.from(Instant.now().plus(Duration.ofDays(1))));
  final GoogleCredentials credentials = UserCredentials.newBuilder()
      .setTokenServerUri(URI.create("http://localhost:" + metadataServer.getPort() + "/get-test-token"))
      .setAccessToken(accessToken)
      .setRefreshToken("user-refresh-token")
      .setClientId("user-id")
      .setClientSecret("user-secret")
      .build();
  Assume.assumeThat(credentials, is(instanceOf(UserCredentials.class)));
  final GoogleIdTokenAuth idTokenAuth = GoogleIdTokenAuth.of(credentials);
  final Optional<String> token = idTokenAuth.getToken("http://styx.foo.bar");
  assertThat(token, is(Optional.of("test-id-token")));

  final RecordedRequest recordedRequest = metadataServer.takeRequest();
  final Map<String, String> requestBody = Splitter.on('&').withKeyValueSeparator('=')
      .split(recordedRequest.getBody().readUtf8());
  assertThat(requestBody, is(ImmutableMap.of(
      "grant_type", "refresh_token",
      "refresh_token", "user-refresh-token",
      "client_id", "user-id",
      "client_secret", "user-secret")));
  assertThat(recordedRequest.getPath(), is("/get-test-token"));
  assertThat(recordedRequest.getHeader("Authorization"), is("Bearer test-access-token"));
}
 
Example #13
Source File: GoogleIdTokenAuth.java    From styx with Apache License 2.0 5 votes vote down vote up
private String getUserToken(UserCredentials credentials) throws IOException {
  log.debug("Fetching user id token");
  final TokenRequest request = new RefreshTokenRequest(
      this.httpTransport, JSON_FACTORY,
      new GenericUrl(credentials.toBuilder().getTokenServerUri()),
      credentials.getRefreshToken())
      .setClientAuthentication(new ClientParametersAuthentication(
          credentials.getClientId(), credentials.getClientSecret()))
      .setRequestInitializer(new HttpCredentialsAdapter(credentials));
  final TokenResponse response = request.execute();
  return (String) response.get("id_token");
}
 
Example #14
Source File: GoogleIdTokenAuth.java    From styx with Apache License 2.0 5 votes vote down vote up
private String getToken(String targetAudience, GoogleCredentials credentials)
    throws IOException, GeneralSecurityException {
  if (credentials instanceof ServiceAccountCredentials) {
    return getServiceAccountToken((ServiceAccountCredentials) credentials, targetAudience);
  } else if (credentials instanceof UserCredentials) {
    return getUserToken((UserCredentials) credentials);
  } else if (credentials instanceof ComputeEngineCredentials) {
    return getDefaultGCEIdToken(targetAudience);
  } else if (credentials instanceof ImpersonatedCredentials) {
    return getImpersonatedIdToken((ImpersonatedCredentials) credentials, targetAudience);
  } else {
    // Assume a type of service account credential
    return getServiceAccountIdTokenUsingAccessToken(credentials, targetAudience);
  }
}
 
Example #15
Source File: AccessTokenProvider.java    From curiostack with MIT License 5 votes vote down vote up
public AccessTokenProvider create(Credentials credentials) {
  if (credentials instanceof UserCredentials) {
    return new UserCredentialsAccessTokenProvider(
        googleAccountsClient, clock, (UserCredentials) credentials);
  } else if (credentials instanceof ServiceAccountCredentials) {
    return new ServiceAccountAccessTokenProvider(
        googleAccountsClient, clock, (ServiceAccountCredentials) credentials);
  } else if (credentials instanceof ComputeEngineCredentials) {
    return new ComputeEngineAccessTokenProvider(googleAccountsClient, clock);
  }
  throw new IllegalArgumentException("Unsupported credentials type: " + credentials);
}
 
Example #16
Source File: UserCredentialsAccessTokenProvider.java    From curiostack with MIT License 5 votes vote down vote up
private static ByteBuf createRefreshRequestContent(UserCredentials credentials) {
  QueryStringEncoder formEncoder = new QueryStringEncoder("");
  formEncoder.addParam("client_id", credentials.getClientId());
  formEncoder.addParam("client_secret", credentials.getClientSecret());
  formEncoder.addParam("refresh_token", credentials.getRefreshToken());
  formEncoder.addParam("grant_type", GRANT_TYPE);
  String contentWithQuestionMark = formEncoder.toString();

  ByteBuf content = Unpooled.buffer(contentWithQuestionMark.length() - 1);
  ByteBufUtil.writeAscii(content, contentWithQuestionMark.substring(1));
  return content;
}
 
Example #17
Source File: Credentials.java    From sample-googleassistant with Apache License 2.0 5 votes vote down vote up
static UserCredentials fromResource(Context context, int resourceId)
        throws IOException, JSONException {
    InputStream is = context.getResources().openRawResource(resourceId);
    byte[] bytes = new byte[is.available()];
    is.read(bytes);
    JSONObject json = new JSONObject(new String(bytes, "UTF-8"));
    return new UserCredentials(
            json.getString("client_id"),
            json.getString("client_secret"),
            json.getString("refresh_token")
    );
}
 
Example #18
Source File: GoogleCredentialsBuilderTest.java    From aiven-kafka-connect-gcs with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
void testCredentialsPathProvided() throws IOException {
    final String credentialsPath =
        getClass().getClassLoader().getResource("test_gcs_credentials.json").getPath();
    final GoogleCredentials credentials = GoogleCredentialsBuilder.build(credentialsPath, null);
    assertTrue(credentials instanceof UserCredentials);

    final UserCredentials userCredentials = (UserCredentials) credentials;
    assertEquals("test-client-id", userCredentials.getClientId());
    assertEquals("test-client-secret", userCredentials.getClientSecret());
}
 
Example #19
Source File: ConfigureClientLibraryProgrammatically.java    From google-ads-java with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
  // Sets up the credentials for Google Ads user authentication.
  UserCredentials credentials =
      UserCredentials.newBuilder()
          .setClientId(OAUTH_CLIENT_ID)
          .setClientSecret(OAUTH_CLIENT_SECRET)
          .setRefreshToken(REFRESH_TOKEN)
          .build();

  // Creates a GoogleAdsClient with the provided credentials.
  GoogleAdsClient client =
      GoogleAdsClient.newBuilder()
          // Sets the developer token which enables API access.
          .setDeveloperToken(DEVELOPER_TOKEN)
          // Sets the OAuth credentials which provide Google Ads account access.
          .setCredentials(credentials)
          // Optional: sets the login customer ID. This is required when the Google account
          // authenticated with the refresh token does not have direct access to
          // OPERATING_CUSTOMER_ID and the access is via a manager account. In this case, specify
          // the manager account ID as LOGIN_CUSTOMER_ID.
          .setLoginCustomerId(Long.valueOf(LOGIN_CUSTOMER_ID))
          .build();

  // Uses the client configured with these credentials.
  try (GoogleAdsServiceClient googleAdsServiceClient =
      client.getLatestVersion().createGoogleAdsServiceClient()) {
    googleAdsServiceClient.search(OPERATING_CUSTOMER_ID, "SELECT campaign.id FROM campaign");
  }
}
 
Example #20
Source File: AuthenticateInStandaloneApplication.java    From google-ads-java with Apache License 2.0 5 votes vote down vote up
public void runExample(String clientId, String clientSecret) throws IOException {
  UserAuthorizer userAuthorizer =
      UserAuthorizer.newBuilder()
          .setClientId(ClientId.of(clientId, clientSecret))
          .setScopes(SCOPES)
          .setCallbackUri(URI.create(CALLBACK_URI))
          .build();
  URL authorizationUrl = userAuthorizer.getAuthorizationUrl(null, null, null);
  System.out.printf("Paste this url in your browser:%n%s%n", authorizationUrl);

  // Waits 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();

  // Exchanges the authorization code for credentials and print the refresh token.
  UserCredentials userCredentials =
      userAuthorizer.getCredentialsFromCode(authorizationCode, null);
  System.out.printf("Your refresh token is: %s%n", userCredentials.getRefreshToken());

  // Prints the configuration file contents.
  Properties adsProperties = new Properties();
  adsProperties.put(ConfigPropertyKey.CLIENT_ID.getPropertyKey(), clientId);
  adsProperties.put(ConfigPropertyKey.CLIENT_SECRET.getPropertyKey(), clientSecret);
  adsProperties.put(
      ConfigPropertyKey.REFRESH_TOKEN.getPropertyKey(), userCredentials.getRefreshToken());
  adsProperties.put(
      ConfigPropertyKey.DEVELOPER_TOKEN.getPropertyKey(), "INSERT_DEVELOPER_TOKEN_HERE");

  showConfigurationFile(adsProperties);
}
 
Example #21
Source File: GoogleAdsClient.java    From google-ads-java with Apache License 2.0 5 votes vote down vote up
private void setCredentials(Properties properties) {
  UserCredentials credentials =
      UserCredentials.newBuilder()
          .setClientId(properties.getProperty(ConfigPropertyKey.CLIENT_ID.getPropertyKey()))
          .setClientSecret(
              properties.getProperty(ConfigPropertyKey.CLIENT_SECRET.getPropertyKey()))
          .setRefreshToken(
              properties.getProperty(ConfigPropertyKey.REFRESH_TOKEN.getPropertyKey()))
          .build();
  setCredentials(credentials);
}
 
Example #22
Source File: GoogleCredentialsBuilderTest.java    From aiven-kafka-connect-gcs with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
void testCredentialsJsonProvided() throws IOException {
    final String credentialsJson = Resources.toString(
        getClass().getClassLoader().getResource("test_gcs_credentials.json"),
        StandardCharsets.UTF_8);
    final GoogleCredentials credentials = GoogleCredentialsBuilder.build(null, credentialsJson);
    assertTrue(credentials instanceof UserCredentials);

    final UserCredentials userCredentials = (UserCredentials) credentials;
    assertEquals("test-client-id", userCredentials.getClientId());
    assertEquals("test-client-secret", userCredentials.getClientSecret());
}
 
Example #23
Source File: UserCredentialsAccessTokenProvider.java    From curiostack with MIT License 4 votes vote down vote up
UserCredentialsAccessTokenProvider(
    WebClient googleAccountsClient, Clock clock, UserCredentials credentials) {
  super(googleAccountsClient, clock);
  refreshRequestContent = createRefreshRequestContent(credentials);
}
 
Example #24
Source File: DefaultCredentialsProvider.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
/**
 * The credentials provided by this object originate from the following sources:
 * <ul>
 *     <li>*.credentials.location: Credentials built from JSON content inside the file pointed
 *     to by this property,</li>
 *     <li>*.credentials.encoded-key: Credentials built from JSON String, encoded on
 *     base64,</li>
 *     <li>Google Cloud Client Libraries default credentials provider.</li>
 * </ul>
 *
 * <p>If credentials are provided by one source, the next sources are discarded.
 * @param credentialsSupplier provides properties that can override OAuth2
 * scopes list used by the credentials, and the location of the OAuth2 credentials private
 * key.
 * @throws IOException if an issue occurs creating the DefaultCredentialsProvider
 */
public DefaultCredentialsProvider(CredentialsSupplier credentialsSupplier) throws IOException {
	List<String> scopes = resolveScopes(credentialsSupplier.getCredentials().getScopes());
	Resource providedLocation = credentialsSupplier.getCredentials().getLocation();
	String encodedKey = credentialsSupplier.getCredentials().getEncodedKey();

	if (!StringUtils.isEmpty(providedLocation)) {
		this.wrappedCredentialsProvider = FixedCredentialsProvider
				.create(GoogleCredentials.fromStream(
						providedLocation.getInputStream())
						.createScoped(scopes));
	}
	else if (!StringUtils.isEmpty(encodedKey)) {
		this.wrappedCredentialsProvider = FixedCredentialsProvider.create(
				GoogleCredentials.fromStream(
						new ByteArrayInputStream(Base64.getDecoder().decode(encodedKey)))
						.createScoped(scopes));
	}
	else {
		this.wrappedCredentialsProvider = GoogleCredentialsProvider.newBuilder()
				.setScopesToApply(scopes)
				.build();
	}

	try {
		Credentials credentials = this.wrappedCredentialsProvider.getCredentials();

		if (LOGGER.isInfoEnabled()) {
			if (credentials instanceof UserCredentials) {
				LOGGER.info("Default credentials provider for user "
						+ ((UserCredentials) credentials).getClientId());
			}
			else if (credentials instanceof ServiceAccountCredentials) {
				LOGGER.info("Default credentials provider for service account "
						+ ((ServiceAccountCredentials) credentials).getClientEmail());
			}
			else if (credentials instanceof ComputeEngineCredentials) {
				LOGGER.info("Default credentials provider for Google Compute Engine.");
			}
			LOGGER.info("Scopes in use by default credentials: " + scopes.toString());
		}
	}
	catch (IOException ioe) {
		LOGGER.warn("No core credentials are set. Service-specific credentials " +
				"(e.g., spring.cloud.gcp.pubsub.credentials.*) should be used if your app uses "
				+ "services that require credentials.", ioe);
	}
}
 
Example #25
Source File: AuthenticateInWebApplication.java    From google-ads-java with Apache License 2.0 4 votes vote down vote up
public void runExample(String clientId, String clientSecret, String loginEmailAddressHint)
    throws Exception {
  // Creates an anti-forgery state token as described here:
  // https://developers.google.com/identity/protocols/OpenIDConnect#createxsrftoken
  String state = new BigInteger(130, new SecureRandom()).toString(32);

  // Creates an HTTP server that will listen for the OAuth2 callback request.
  URI baseUri;
  UserAuthorizer userAuthorizer;
  AuthorizationResponse authorizationResponse = null;
  try (SimpleCallbackServer simpleCallbackServer = new SimpleCallbackServer()) {
    userAuthorizer =
        UserAuthorizer.newBuilder()
            .setClientId(ClientId.of(clientId, clientSecret))
            .setScopes(SCOPES)
            .setCallbackUri(URI.create(OAUTH2_CALLBACK))
            .build();
    baseUri = URI.create("http://localhost:" + simpleCallbackServer.getLocalPort());
    System.out.printf(
        "Paste this url in your browser:%n%s%n",
        userAuthorizer.getAuthorizationUrl(loginEmailAddressHint, state, baseUri));

    // Waits for the authorization code.
    simpleCallbackServer.accept();
    authorizationResponse = simpleCallbackServer.authorizationResponse;
  }

  if (authorizationResponse == null || authorizationResponse.code == null) {
    throw new NullPointerException(
        "OAuth2 callback did not contain an authorization code: " + authorizationResponse);
  }

  // Confirms that the state in the response matches the state token used to generate the
  // authorization URL.
  if (!state.equals(authorizationResponse.state)) {
    throw new IllegalStateException("State does not match expected state");
  }

  // Exchanges the authorization code for credentials and print the refresh token.
  UserCredentials userCredentials =
      userAuthorizer.getCredentialsFromCode(authorizationResponse.code, baseUri);
  System.out.printf("Your refresh token is: %s%n", userCredentials.getRefreshToken());

  // Prints the configuration file contents.
  Properties adsProperties = new Properties();
  adsProperties.put(ConfigPropertyKey.CLIENT_ID.getPropertyKey(), clientId);
  adsProperties.put(ConfigPropertyKey.CLIENT_SECRET.getPropertyKey(), clientSecret);
  adsProperties.put(
      ConfigPropertyKey.REFRESH_TOKEN.getPropertyKey(), userCredentials.getRefreshToken());
  adsProperties.put(
      ConfigPropertyKey.DEVELOPER_TOKEN.getPropertyKey(), "INSERT_DEVELOPER_TOKEN_HERE");

  showConfigurationFile(adsProperties);
}
 
Example #26
Source File: GoogleIdTokenAuthTest.java    From styx with Apache License 2.0 4 votes vote down vote up
@Test
public void testUserCredentials() throws IOException, GeneralSecurityException {
  Assume.assumeThat(credentials, is(instanceOf(UserCredentials.class)));
  assertThat(canAcquireIdToken(credentials), is(true));
}
 
Example #27
Source File: GcsSinkConfigTest.java    From aiven-kafka-connect-gcs with GNU Affero General Public License v3.0 4 votes vote down vote up
@Test
void gcsCredentialsPath() {
    final Map<String, String> properties = new HashMap<>();
    properties.put("gcs.bucket.name", "test-bucket");
    properties.put(
        "gcs.credentials.path",
        getClass().getClassLoader().getResource("test_gcs_credentials.json").getPath());

    final GcsSinkConfig config = new GcsSinkConfig(properties);
    final UserCredentials credentials = (UserCredentials) config.getCredentials();
    assertEquals("test-client-id", credentials.getClientId());
    assertEquals("test-client-secret", credentials.getClientSecret());
}
 
Example #28
Source File: EmbeddedAssistant.java    From sample-googleassistant with Apache License 2.0 2 votes vote down vote up
/**
 * Generates access tokens for the Assistant based on a credentials JSON file.
 *
 * @param context Application context
 * @param resourceId The resource that contains the project credentials
 *
 * @return A {@link UserCredentials} object which can be used by the Assistant.
 * @throws IOException If the resource does not exist.
 * @throws JSONException If the resource is incorrectly formatted.
 */
public static UserCredentials generateCredentials(Context context, int resourceId)
        throws IOException, JSONException {
    return Credentials.fromResource(context, resourceId);
}
 
Example #29
Source File: EmbeddedAssistant.java    From sample-googleassistant with Apache License 2.0 2 votes vote down vote up
/**
 * Sets the credentials for the user.
 *
 * @param userCredentials Credentials generated by
 *    {@link EmbeddedAssistant#generateCredentials(Context, int)}.
 * @return Returns this builder to allow for chaining.
 */
public Builder setCredentials(UserCredentials userCredentials) {
    mEmbeddedAssistant.mUserCredentials = userCredentials;
    return this;
}