Java Code Examples for com.google.api.client.auth.oauth2.Credential#getAccessToken()

The following examples show how to use com.google.api.client.auth.oauth2.Credential#getAccessToken() . 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: DatastoreImpl.java    From async-datastore-client with Apache License 2.0 6 votes vote down vote up
void refreshAccessToken() {
  final Credential credential = config.getCredential();
  final Long expiresIn = credential.getExpiresInSeconds();

  // trigger refresh if token is null or is about to expire
  if (credential.getAccessToken() == null
      || expiresIn != null && expiresIn <= 60) {
    try {
      credential.refreshToken();
    } catch (final IOException e) {
      log.error("Storage exception", Throwables.getRootCause(e));
    }
  }

  // update local token if the credentials token has refreshed since last update
  final String accessTokenLocal = credential.getAccessToken();

  if (this.accessToken == null || !accessToken.equals(accessTokenLocal)) {
      this.accessToken = accessTokenLocal;
  }
}
 
Example 2
Source File: OAuthManager.java    From mirror with Apache License 2.0 5 votes vote down vote up
/**
 * Authorizes the Android application to access user's protected data using
 * the Implicit Authorization flow in OAuth 2.0.
 *
 * @param userId   user ID or {@code null} if not using a persisted credential
 *                 store
 * @param callback Callback to invoke when the request completes,
 *                 {@code null} for no callback
 * @param handler  {@link Handler} identifying the callback thread,
 *                 {@code null} for the main thread
 * @return An {@link OAuthFuture} which resolves to a {@link Credential}
 */
public OAuthFuture<Credential> authorizeImplicitly(final String userId,
                                                   final OAuthCallback<Credential> callback, Handler handler) {
    Preconditions.checkNotNull(userId);
    final Future2Task<Credential> task = new Future2Task<Credential>(handler, callback) {
        @Override
        public void doWork() throws Exception {
            try {
                Timber.i("authorizeImplicitly");
                Credential credential = mFlow.loadCredential(userId);
                if (credential != null && credential.getAccessToken() != null
                        && (credential.getRefreshToken() != null ||
                        credential.getExpiresInSeconds() == null ||
                        credential.getExpiresInSeconds() > 60)) {
                    set(credential);
                    return;
                }

                BrowserClientRequestUrl authorizationUrl = mFlow.newImplicitAuthorizationUrl()
                        .setRedirectUri(mUIController.getRedirectUri());
                mUIController.requestAuthorization(authorizationUrl);

                ImplicitResponseUrl implicitResponse = mUIController.waitForImplicitResponseUrl();
                credential = mFlow.createAndStoreCredential(implicitResponse, userId);
                set(credential);
            } finally {
                mUIController.stop();
            }
        }
    };

    // run the task in a background thread
    submitTaskToExecutor(task);

    return task;
}
 
Example 3
Source File: GetUserProfile.java    From rides-java-sdk with MIT License 5 votes vote down vote up
/**
 * Authenticate the given user. If you are distributing an installed application, this method
 * should exist on your server so that the client ID and secret are not shared with the end
 * user.
 */
private static Credential authenticate(String userId, SessionConfiguration config) throws Exception {
    OAuth2Credentials oAuth2Credentials = createOAuth2Credentials(config);

    // First try to load an existing Credential. If that credential is null, authenticate the user.
    Credential credential = oAuth2Credentials.loadCredential(userId);
    if (credential == null || credential.getAccessToken() == null) {
        // Send user to authorize your application.
        System.out.printf("Add the following redirect URI to your developer.uber.com application: %s%n",
                oAuth2Credentials.getRedirectUri());
        System.out.println("Press Enter when done.");

        System.in.read();

        // Generate an authorization URL.
        String authorizationUrl = oAuth2Credentials.getAuthorizationUrl();
        System.out.printf("In your browser, navigate to: %s%n", authorizationUrl);
        System.out.println("Waiting for authentication...");

        // Wait for the authorization code.
        String authorizationCode = localServerReceiver.waitForCode();
        System.out.println("Authentication received.");

        // Authenticate the user with the authorization code.
        credential = oAuth2Credentials.authenticate(authorizationCode, userId);
    }
    localServerReceiver.stop();

    return credential;
}
 
Example 4
Source File: PKCESample.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    try {
        DATA_STORE_FACTORY = new MemoryDataStoreFactory();
        final Credential credential = authorize();
        System.out.println("Successfully obtained credential from Keycloak running on localhost.");
        final String accessToken = credential.getAccessToken();
        System.out.println("Retrieved an access token of length " + accessToken.length());
        return;
    } catch (IOException e) {
        System.err.println(e.getMessage());
    } catch (Throwable t) {
        t.printStackTrace();
    }
    System.exit(1);
}
 
Example 5
Source File: FilePersistedCredential.java    From android-oauth-client with Apache License 2.0 5 votes vote down vote up
/**
 * Store information from the credential.
 *
 * @param credential credential whose {@link Credential#getAccessToken access token},
 *        {@link Credential#getRefreshToken refresh token}, and
 *        {@link Credential#getExpirationTimeMilliseconds expiration time} need to be stored
 */
void store(Credential credential) {
  accessToken = credential.getAccessToken();
  refreshToken = credential.getRefreshToken();
  expirationTimeMillis = credential.getExpirationTimeMilliseconds();
  if (credential instanceof OAuthHmacCredential) {
      OAuthHmacCredential oauth10aCredential = (OAuthHmacCredential) credential;
      tokenSharedSecret = oauth10aCredential.getTokenSharedSecret();
      consumerKey = oauth10aCredential.getConsumerKey();
      sharedSecret = oauth10aCredential.getSharedSecret();
  }
}
 
Example 6
Source File: OAuth2Helper.java    From googleads-java-lib with Apache License 2.0 4 votes vote down vote up
/**
 * Returns {@code true} if the credential can and should be refreshed.
 */
@VisibleForTesting
boolean isCredentialRefreshable(Credential credential) {
  return credential.getAccessToken() == null || credential.getExpiresInSeconds() != null
      && credential.getExpiresInSeconds() <= refreshWindowSeconds;
}
 
Example 7
Source File: AddGoogleMyBusinessLocationExtensions.java    From googleads-java-lib with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
  AdWordsSession session;
  Credential oAuth2Credential;
  try {
    // Generate a refreshable OAuth2 credential.
    oAuth2Credential =
        new OfflineCredentials.Builder()
            .forApi(Api.ADWORDS)
            .fromFile()
            .build()
            .generateCredential();

    // Construct an AdWordsSession.
    session =
        new AdWordsSession.Builder().fromFile().withOAuth2Credential(oAuth2Credential).build();
  } catch (ConfigurationLoadException cle) {
    System.err.printf(
        "Failed to load configuration from the %s file. Exception: %s%n",
        DEFAULT_CONFIGURATION_FILENAME, cle);
    return;
  } catch (ValidationException ve) {
    System.err.printf(
        "Invalid configuration in the %s file. Exception: %s%n",
        DEFAULT_CONFIGURATION_FILENAME, ve);
    return;
  } catch (OAuthException oe) {
    System.err.printf(
        "Failed to create OAuth credentials. Check OAuth settings in the %s file. "
            + "Exception: %s%n",
        DEFAULT_CONFIGURATION_FILENAME, oe);
    return;
  }

  AdWordsServicesInterface adWordsServices = AdWordsServices.getInstance();

  AddGoogleMyBusinessLocationExtensionsParams params =
      new AddGoogleMyBusinessLocationExtensionsParams();
  if (!params.parseArguments(args)) {
    // Either pass the required parameters for this example on the command line, or insert them
    // into the code here. See the parameter class definition above for descriptions.
    params.gmbEmailAddress = "INSERT_GMB_EMAIL_ADDRESS_HERE";
    params.gmbAccessToken = oAuth2Credential.getAccessToken();
    params.businessAccountIdentifier = "INSERT_BUSINESS_ACCOUNT_IDENTIFIER_HERE";
  }

  try {
    runExample(adWordsServices, session, params.gmbEmailAddress, params.gmbAccessToken,
        params.businessAccountIdentifier);
  } catch (ApiException apiException) {
    // ApiException is the base class for most exceptions thrown by an API request. Instances
    // of this exception have a message and a collection of ApiErrors that indicate the
    // type and underlying cause of the exception. Every exception object in the adwords.axis
    // packages will return a meaningful value from toString
    //
    // ApiException extends RemoteException, so this catch block must appear before the
    // catch block for RemoteException.
    System.err.println("Request failed due to ApiException. Underlying ApiErrors:");
    if (apiException.getErrors() != null) {
      int i = 0;
      for (ApiError apiError : apiException.getErrors()) {
        System.err.printf("  Error %d: %s%n", i++, apiError);
      }
    }
  } catch (RemoteException re) {
    System.err.printf(
        "Request failed unexpectedly due to RemoteException: %s%n", re);
  } catch (InterruptedException ie) {
    System.err.printf("Thread was interrupted: %s%n", ie);
  }
}
 
Example 8
Source File: OAuthManager.java    From android-oauth-client with Apache License 2.0 4 votes vote down vote up
/**
 * Authorizes the Android application to access user's protected data using
 * the Explicit Authorization Code flow in OAuth 2.0.
 * 
 * @param userId user ID or {@code null} if not using a persisted credential
 *            store
 * @param callback Callback to invoke when the request completes,
 *            {@code null} for no callback
 * @param handler {@link Handler} identifying the callback thread,
 *            {@code null} for the main thread
 * @return An {@link OAuthFuture} which resolves to a {@link Credential}
 */
public OAuthFuture<Credential> authorizeExplicitly(final String userId,
        final OAuthCallback<Credential> callback, Handler handler) {
    Preconditions.checkNotNull(userId);

    final Future2Task<Credential> task = new Future2Task<Credential>(handler, callback) {

        @Override
        public void doWork() throws Exception {
            try {
                Credential credential = mFlow.loadCredential(userId);
                LOGGER.info("authorizeExplicitly");
                if (credential != null && credential.getAccessToken() != null
                        && (credential.getRefreshToken() != null ||
                                credential.getExpiresInSeconds() == null ||
                        credential.getExpiresInSeconds() > 60)) {
                    set(credential);
                    return;
                }

                String redirectUri = mUIController.getRedirectUri();

                AuthorizationCodeRequestUrl authorizationUrl = mFlow
                        .newExplicitAuthorizationUrl()
                        .setRedirectUri(redirectUri);
                mUIController.requestAuthorization(authorizationUrl);

                String code = mUIController.waitForExplicitCode();
                TokenResponse response = mFlow.newTokenRequest(code)
                        .setRedirectUri(redirectUri).execute();
                credential = mFlow.createAndStoreCredential(response, userId);
                set(credential);
            } finally {
                mUIController.stop();
            }
        }

    };

    // run the task in a background thread
    submitTaskToExecutor(task);

    return task;
}
 
Example 9
Source File: OAuthManager.java    From android-oauth-client with Apache License 2.0 4 votes vote down vote up
/**
 * Authorizes the Android application to access user's protected data using
 * the Implicit Authorization flow in OAuth 2.0.
 * 
 * @param userId user ID or {@code null} if not using a persisted credential
 *            store
 * @param callback Callback to invoke when the request completes,
 *            {@code null} for no callback
 * @param handler {@link Handler} identifying the callback thread,
 *            {@code null} for the main thread
 * @return An {@link OAuthFuture} which resolves to a {@link Credential}
 */
public OAuthFuture<Credential> authorizeImplicitly(final String userId,
        final OAuthCallback<Credential> callback, Handler handler) {
    Preconditions.checkNotNull(userId);

    final Future2Task<Credential> task = new Future2Task<Credential>(handler, callback) {

        @Override
        public void doWork() throws TokenResponseException, Exception {
            try {
                LOGGER.info("authorizeImplicitly");
                Credential credential = mFlow.loadCredential(userId);
                if (credential != null && credential.getAccessToken() != null
                        && (credential.getRefreshToken() != null ||
                                credential.getExpiresInSeconds() == null ||
                        credential.getExpiresInSeconds() > 60)) {
                    set(credential);
                    return;
                }

                String redirectUri = mUIController.getRedirectUri();

                BrowserClientRequestUrl authorizationUrl = mFlow.newImplicitAuthorizationUrl()
                        .setRedirectUri(redirectUri);
                mUIController.requestAuthorization(authorizationUrl);

                ImplicitResponseUrl implicitResponse = mUIController
                        .waitForImplicitResponseUrl();
                credential = mFlow.createAndStoreCredential(implicitResponse, userId);
                set(credential);
            } finally {
                mUIController.stop();
            }
        }

    };

    // run the task in a background thread
    submitTaskToExecutor(task);

    return task;
}
 
Example 10
Source File: FilePersistedCredential.java    From mirror with Apache License 2.0 2 votes vote down vote up
/**
 * Store information from the credential.
 *
 * @param credential credential whose {@link Credential#getAccessToken access token},
 *        {@link Credential#getRefreshToken refresh token}, and
 *        {@link Credential#getExpirationTimeMilliseconds expiration time} need to be stored
 */
void store(Credential credential) {
  accessToken = credential.getAccessToken();
  refreshToken = credential.getRefreshToken();
  expirationTimeMillis = credential.getExpirationTimeMilliseconds();
}
 
Example 11
Source File: FilePersistedCredential.java    From google-oauth-java-client with Apache License 2.0 2 votes vote down vote up
/**
 * Store information from the credential.
 *
 * @param credential credential whose {@link Credential#getAccessToken access token},
 *        {@link Credential#getRefreshToken refresh token}, and
 *        {@link Credential#getExpirationTimeMilliseconds expiration time} need to be stored
 */
void store(Credential credential) {
  accessToken = credential.getAccessToken();
  refreshToken = credential.getRefreshToken();
  expirationTimeMillis = credential.getExpirationTimeMilliseconds();
}