Java Code Examples for com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow#loadCredential()

The following examples show how to use com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow#loadCredential() . 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: AdvancedCreateCredentialFromScratch.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
private static AdManagerSession createDfpSession(DataStoreFactory storeFactory, String userId)
    throws IOException, ValidationException, ConfigurationLoadException {

  // Create a GoogleCredential with minimal information.
  GoogleAuthorizationCodeFlow authorizationFlow =
      new GoogleAuthorizationCodeFlow.Builder(
              new NetHttpTransport(),
              new JacksonFactory(),
              CLIENT_ID,
              CLIENT_SECRET,
              Arrays.asList(SCOPE))
          .setDataStoreFactory(storeFactory)
          .build();

  // Load the credential.
  Credential credential = authorizationFlow.loadCredential(userId);

  // Construct a AdManagerSession.
  return new AdManagerSession.Builder().fromFile().withOAuth2Credential(credential).build();
}
 
Example 2
Source File: AdvancedCreateCredentialFromScratch.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
private static AdWordsSession createAdWordsSession(String userId, DataStoreFactory storeFactory)
    throws IOException, ValidationException, ConfigurationLoadException {
  // Create a GoogleCredential with minimal information.
  GoogleAuthorizationCodeFlow authorizationFlow = new GoogleAuthorizationCodeFlow.Builder(
      new NetHttpTransport(),
      new JacksonFactory(),
      CLIENT_ID,
      CLIENT_SECRET,
      Arrays.asList(SCOPE))
      .setDataStoreFactory(storeFactory)
      .build();

  // Load the credential.
  Credential credential = authorizationFlow.loadCredential(userId);

  // Construct an AdWordsSession using the default ads.properties file to set the session's
  // developer token, client customer ID, etc., but use the credentials created above.
  return new AdWordsSession.Builder()
      .fromFile()
      .withOAuth2Credential(credential)
      .build();
}
 
Example 3
Source File: SearchHelper.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
private static Credential createCredentials(
    HttpTransport httpTransport, SearchAuthInfo searchAuthInfo)
    throws IOException {
  GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(
      JSON_FACTORY, new InputStreamReader(searchAuthInfo.getClientSecretsStream(), UTF_8));
  GoogleAuthorizationCodeFlow flow =
      new GoogleAuthorizationCodeFlow.Builder(
          httpTransport, JSON_FACTORY, clientSecrets, API_SCOPES)
          .setDataStoreFactory(new FileDataStoreFactory(searchAuthInfo.getCredentialsDirectory()))
          .build();
  return flow.loadCredential(searchAuthInfo.getUserEmail());
}
 
Example 4
Source File: AuthModule.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Provides
@StoredCredential
static Credential provideCredential(
    GoogleAuthorizationCodeFlow flow, @ClientScopeQualifier String clientScopeQualifier) {
  try {
    // Try to load the credentials, throw an exception if we fail.
    Credential credential = flow.loadCredential(clientScopeQualifier);
    if (credential == null) {
      throw new LoginRequiredException();
    }
    return credential;
  } catch (IOException ex) {
    throw new RuntimeException(ex);
  }
}
 
Example 5
Source File: Authorizer.java    From mail-importer with Apache License 2.0 4 votes vote down vote up
public Credential get() {
  try {
    GoogleClientSecrets clientSecrets = loadGoogleClientSecrets(jsonFactory);

    DataStore<StoredCredential> dataStore = getStoredCredentialDataStore();

    // Allow user to authorize via url.
    GoogleAuthorizationCodeFlow flow =
        new GoogleAuthorizationCodeFlow.Builder(
            httpTransport,
            jsonFactory,
            clientSecrets,
            ImmutableList.of(
                GmailScopes.GMAIL_MODIFY,
                GmailScopes.GMAIL_READONLY))
            .setCredentialDataStore(dataStore)
            .setAccessType("offline")
            .setApprovalPrompt("auto")
            .build();

    // First, see if we have a stored credential for the user.
    Credential credential = flow.loadCredential(user.getEmailAddress());

    // If we don't, prompt them to get one.
    if (credential == null) {
      String url = flow.newAuthorizationUrl()
          .setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI)
          .build();
      System.out.println("Please open the following URL in your browser then "
          + "type the authorization code:\n" + url);

      // Read code entered by user.
      System.out.print("Code: ");
      System.out.flush();
      BufferedReader br = new BufferedReader(
          new InputStreamReader(System.in));
      String code = br.readLine();

      // Generate Credential using retrieved code.
      GoogleTokenResponse response = flow.newTokenRequest(code)
          .setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI)
          .execute();

      credential =
          flow.createAndStoreCredential(response, user.getEmailAddress());
    }

    Gmail gmail = new Gmail.Builder(httpTransport, jsonFactory, credential)
        .setApplicationName(GmailServiceModule.APP_NAME)
        .build();

    Profile profile = gmail.users()
        .getProfile(user.getEmailAddress())
        .execute();

    System.out.println(profile.toPrettyString());
    return credential;
  } catch (IOException exception) {
    throw new RuntimeException(exception);
  }
}