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

The following examples show how to use com.google.api.client.auth.oauth2.Credential#getRefreshToken() . 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: AuthorizationCodeInstalledApp.java    From google-oauth-java-client with Apache License 2.0 6 votes vote down vote up
/**
 * Authorizes the installed application to access user's protected data.
 *
 * @param userId user ID or {@code null} if not using a persisted credential store
 * @return credential
 */
public Credential authorize(String userId) throws IOException {
  try {
    Credential credential = flow.loadCredential(userId);
    if (credential != null
        && (credential.getRefreshToken() != null ||
            credential.getExpiresInSeconds() == null ||
            credential.getExpiresInSeconds() > 60)) {
      return credential;
    }
    // open in browser
    String redirectUri = receiver.getRedirectUri();
    AuthorizationCodeRequestUrl authorizationUrl =
        flow.newAuthorizationUrl().setRedirectUri(redirectUri);
    onAuthorization(authorizationUrl);
    // receive authorization code and exchange it for an access token
    String code = receiver.waitForCode();
    TokenResponse response = flow.newTokenRequest(code).setRedirectUri(redirectUri).execute();
    // store credential and return it
    return flow.createAndStoreCredential(response, userId);
  } finally {
    receiver.stop();
  }
}
 
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: 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 4
Source File: InstalledOAuth2Authenticator.java    From adwords-alerting with Apache License 2.0 4 votes vote down vote up
/**
 * Get New Credentials from the user from the command line OAuth2 dance.
 */
private Credential getNewOAuth2Credential() throws OAuthException {
  GoogleAuthorizationCodeFlow authorizationFlow = getAuthorizationFlow();
  String authorizeUrl =
      authorizationFlow.newAuthorizationUrl().setRedirectUri(CALLBACK_URL).build();

  System.out.println("\n**ACTION REQUIRED** Paste this url in your browser"
      + " and authenticate using your **AdWords Admin Email**: \n" + authorizeUrl);

  // Wait for the authorization code.
  System.out.println("\nType the code you received on the web page here: ");
  try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    String authorizationCode = reader.readLine();

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

    //  Create the credential.
    Credential credential =
        new GoogleCredential.Builder()
            .setClientSecrets(clientId, clientSecret)
            .setJsonFactory(new JacksonFactory())
            .setTransport(new NetHttpTransport())
            .build()
            .setFromTokenResponse(tokenResponse);

    // Get refresh token and prompt to save in properties file
    refreshToken = credential.getRefreshToken();
    System.out.println("\n**ACTION REQUIRED** Put the following line in your properties file to"
        + " avoid OAuth authentication next time.");
    System.out.printf("refreshToken=%s\n\n", refreshToken);

    System.out.println("Then press enter to continue...");
    reader.readLine();

    return credential;
  } catch (IOException e) {
    throw new OAuthException("An error occured obtaining the OAuth2Credential", e.getCause());
  }
}
 
Example 5
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 6
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 7
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 8
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();
}