Search in sources :

Example 16 with Builder

use of com.google.api.client.auth.oauth2.AuthorizationCodeFlow.Builder in project hub-alert by blackducksoftware.

the class AzureAuthorizationCodeFlowTest method builderTest.

@Test
public void builderTest() {
    AzureAuthorizationCodeFlow.Builder builder = new AzureAuthorizationCodeFlow.Builder(method, httpTransport, jsonFactory, genericUrl, clientAuthentication, clientId, authorizationServerEncodedUrl, null, null);
    assertNull(builder.getClientSecret());
    assertNull(builder.getRedirectUri());
    builder.setClientSecret(clientSecret);
    builder.setRedirectUri(redirectUri);
    assertEquals(clientSecret, builder.getClientSecret());
    assertEquals(redirectUri, builder.getRedirectUri());
    AuthorizationCodeFlow azureAuthorizationCodeFlow = builder.build();
    AuthorizationCodeTokenRequest tokenRequest = azureAuthorizationCodeFlow.newTokenRequest(authorizationCode);
    testAuthorizationCodeTokenRequest(tokenRequest);
}
Also used : AuthorizationCodeTokenRequest(com.google.api.client.auth.oauth2.AuthorizationCodeTokenRequest) AuthorizationCodeFlow(com.google.api.client.auth.oauth2.AuthorizationCodeFlow) Test(org.junit.jupiter.api.Test)

Example 17 with Builder

use of com.google.api.client.auth.oauth2.AuthorizationCodeFlow.Builder in project OsmAnd-tools by osmandapp.

the class UpdateSubscription method getPublisherApi.

public static AndroidPublisher getPublisherApi(String file) throws JSONException, IOException, GeneralSecurityException {
    List<String> scopes = new ArrayList<String>();
    scopes.add("https://www.googleapis.com/auth/androidpublisher");
    File dataStoreDir = new File(new File(file).getParentFile(), ".credentials");
    JacksonFactory jsonFactory = new com.google.api.client.json.jackson2.JacksonFactory();
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(jsonFactory, new InputStreamReader(new FileInputStream(file)));
    NetHttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory, clientSecrets, scopes).setDataStoreFactory(new FileDataStoreFactory(dataStoreDir)).setAccessType("offline").build();
    Builder bld = new LocalServerReceiver.Builder();
    bld.setPort(5000);
    // it only works with localhost ! with other hosts gives incorrect redirect uri (looks like it's not supported for service accounts)
    // bld.setHost(serverPublicUrl);
    Credential credential = new AuthorizationCodeInstalledApp(flow, bld.build()).authorize("user");
    System.out.println("Credentials saved to " + dataStoreDir.getAbsolutePath());
    AndroidPublisher publisher = new AndroidPublisher.Builder(httpTransport, jsonFactory, credential).setApplicationName(GOOGLE_PRODUCT_NAME).build();
    return publisher;
}
Also used : Credential(com.google.api.client.auth.oauth2.Credential) InputStreamReader(java.io.InputStreamReader) AndroidPublisher(com.google.api.services.androidpublisher.AndroidPublisher) Builder(com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver.Builder) ArrayList(java.util.ArrayList) GoogleAuthorizationCodeFlow(com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow) AuthorizationCodeInstalledApp(com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp) JacksonFactory(com.google.api.client.json.jackson2.JacksonFactory) FileInputStream(java.io.FileInputStream) FileDataStoreFactory(com.google.api.client.util.store.FileDataStoreFactory) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) GoogleNetHttpTransport(com.google.api.client.googleapis.javanet.GoogleNetHttpTransport) GoogleClientSecrets(com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets) File(java.io.File)

Example 18 with Builder

use of com.google.api.client.auth.oauth2.AuthorizationCodeFlow.Builder in project googleads-java-lib by googleads.

the class GetCampaignsByLabel method runExample.

/**
 * Runs the example.
 *
 * @param adWordsServices the services factory.
 * @param session the session.
 * @param labelId the ID of the label.
 * @throws ApiException if the API request failed with one or more service errors.
 * @throws RemoteException if the API request failed due to other errors.
 */
public static void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session, Long labelId) throws RemoteException {
    // Get the CampaignService.
    CampaignServiceInterface campaignService = adWordsServices.get(session, CampaignServiceInterface.class);
    int offset = 0;
    // Create selector.
    SelectorBuilder builder = new SelectorBuilder();
    Selector selector = builder.fields(CampaignField.Id, CampaignField.Name, CampaignField.Labels).containsAny(CampaignField.Labels, labelId.toString()).orderAscBy(CampaignField.Name).offset(offset).limit(PAGE_SIZE).build();
    CampaignPage page = null;
    do {
        // Get all campaigns.
        page = campaignService.get(selector);
        // Display campaigns.
        if (page.getEntries() != null) {
            for (Campaign campaign : page.getEntries()) {
                String labels = Joiner.on(", ").join(Lists.transform(Lists.newArrayList(campaign.getLabels()), label -> String.format("%d/%s", label.getId(), label.getName())));
                System.out.printf("Campaign found with name '%s' and ID %d and labels: %s.%n", campaign.getName(), campaign.getId(), labels);
            }
        } else {
            System.out.println("No campaigns were found.");
        }
        offset += PAGE_SIZE;
        selector = builder.increaseOffsetBy(PAGE_SIZE).build();
    } while (offset < page.getTotalNumEntries());
}
Also used : OAuthException(com.google.api.ads.common.lib.exception.OAuthException) Parameter(com.beust.jcommander.Parameter) AdWordsServices(com.google.api.ads.adwords.axis.factory.AdWordsServices) ConfigurationLoadException(com.google.api.ads.common.lib.conf.ConfigurationLoadException) Campaign(com.google.api.ads.adwords.axis.v201809.cm.Campaign) CampaignServiceInterface(com.google.api.ads.adwords.axis.v201809.cm.CampaignServiceInterface) CampaignPage(com.google.api.ads.adwords.axis.v201809.cm.CampaignPage) CodeSampleParams(com.google.api.ads.common.lib.utils.examples.CodeSampleParams) SelectorBuilder(com.google.api.ads.adwords.axis.utils.v201809.SelectorBuilder) RemoteException(java.rmi.RemoteException) DEFAULT_CONFIGURATION_FILENAME(com.google.api.ads.common.lib.utils.Builder.DEFAULT_CONFIGURATION_FILENAME) AdWordsSession(com.google.api.ads.adwords.lib.client.AdWordsSession) AdWordsServicesInterface(com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface) Lists(com.google.common.collect.Lists) ApiError(com.google.api.ads.adwords.axis.v201809.cm.ApiError) ValidationException(com.google.api.ads.common.lib.exception.ValidationException) CampaignField(com.google.api.ads.adwords.lib.selectorfields.v201809.cm.CampaignField) OfflineCredentials(com.google.api.ads.common.lib.auth.OfflineCredentials) ApiException(com.google.api.ads.adwords.axis.v201809.cm.ApiException) Api(com.google.api.ads.common.lib.auth.OfflineCredentials.Api) Selector(com.google.api.ads.adwords.axis.v201809.cm.Selector) ArgumentNames(com.google.api.ads.adwords.lib.utils.examples.ArgumentNames) Credential(com.google.api.client.auth.oauth2.Credential) Joiner(com.google.common.base.Joiner) CampaignServiceInterface(com.google.api.ads.adwords.axis.v201809.cm.CampaignServiceInterface) Campaign(com.google.api.ads.adwords.axis.v201809.cm.Campaign) SelectorBuilder(com.google.api.ads.adwords.axis.utils.v201809.SelectorBuilder) CampaignPage(com.google.api.ads.adwords.axis.v201809.cm.CampaignPage) Selector(com.google.api.ads.adwords.axis.v201809.cm.Selector)

Example 19 with Builder

use of com.google.api.client.auth.oauth2.AuthorizationCodeFlow.Builder in project isaac-api by isaacphysics.

the class FacebookAuthenticator method exchangeCode.

@Override
public String exchangeCode(final String authorizationCode) throws CodeExchangeException {
    try {
        AuthorizationCodeTokenRequest request = new AuthorizationCodeTokenRequest(httpTransport, jsonFactory, new GenericUrl(TOKEN_EXCHANGE_URL), authorizationCode);
        request.setClientAuthentication(new ClientParametersAuthentication(clientId, clientSecret));
        request.setRedirectUri(callbackUri);
        TokenResponse response = request.execute();
        String accessToken;
        Long expires;
        if (response.get("error") != null) {
            throw new CodeExchangeException("Server responded with the following error" + response.get("error") + " given the request" + request.toString());
        }
        if (response.getAccessToken() != null && response.getExpiresInSeconds() != null) {
            accessToken = response.getAccessToken();
            expires = response.getExpiresInSeconds();
        } else {
            throw new IOException("access_token or expires_in values were not found");
        }
        TokenResponse tokenResponse = new TokenResponse();
        tokenResponse.setAccessToken(accessToken);
        tokenResponse.setExpiresInSeconds(expires);
        // I don't really want to use the flow storage but it seems to be
        // easier to get credentials this way.
        Builder builder = new AuthorizationCodeFlow.Builder(BearerToken.authorizationHeaderAccessMethod(), httpTransport, jsonFactory, new GenericUrl(TOKEN_EXCHANGE_URL), new ClientParametersAuthentication(clientId, clientSecret), clientId, AUTH_URL);
        builder.setScopes(requestedScopes);
        AuthorizationCodeFlow flow = builder.setDataStoreFactory(MemoryDataStoreFactory.getDefaultInstance()).build();
        Credential credential = flow.createAndStoreCredential(tokenResponse, authorizationCode);
        String internalReferenceToken = UUID.randomUUID().toString();
        credentialStore.put(internalReferenceToken, credential);
        flow.getCredentialDataStore().clear();
        return internalReferenceToken;
    } catch (IOException e) {
        String message = "An error occurred during code exchange";
        throw new CodeExchangeException(message, e);
    }
}
Also used : ClientParametersAuthentication(com.google.api.client.auth.oauth2.ClientParametersAuthentication) Credential(com.google.api.client.auth.oauth2.Credential) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) AuthorizationCodeTokenRequest(com.google.api.client.auth.oauth2.AuthorizationCodeTokenRequest) Builder(com.google.api.client.auth.oauth2.AuthorizationCodeFlow.Builder) CodeExchangeException(uk.ac.cam.cl.dtg.segue.auth.exceptions.CodeExchangeException) GenericUrl(com.google.api.client.http.GenericUrl) IOException(java.io.IOException) AuthorizationCodeFlow(com.google.api.client.auth.oauth2.AuthorizationCodeFlow)

Example 20 with Builder

use of com.google.api.client.auth.oauth2.AuthorizationCodeFlow.Builder in project isaac-api by isaacphysics.

the class GoogleAuthenticator method getUserInfo.

@Override
public synchronized UserFromAuthProvider getUserInfo(final String internalProviderReference) throws NoUserException, AuthenticatorSecurityException {
    Credential credentials = credentialStore.getIfPresent(internalProviderReference);
    if (verifyAccessTokenIsValid(credentials)) {
        log.debug("Successful Verification of access token with provider.");
    } else {
        log.error("Unable to verify access token - it could be an indication of fraud.");
        throw new AuthenticatorSecurityException("Access token is invalid - the client id returned by the identity provider does not match ours.");
    }
    Oauth2 userInfoService = new Oauth2.Builder(new NetHttpTransport(), new JacksonFactory(), credentials).setApplicationName(Constants.APPLICATION_NAME).build();
    Userinfo userInfo = null;
    try {
        userInfo = userInfoService.userinfo().get().execute();
        log.debug("Retrieved User info from google: " + userInfo.toPrettyString());
    } catch (IOException e) {
        log.error("An IO error occurred while trying to retrieve user information: " + e);
    }
    if (userInfo != null && userInfo.getId() != null) {
        EmailVerificationStatus emailStatus = userInfo.isVerifiedEmail() ? EmailVerificationStatus.VERIFIED : EmailVerificationStatus.NOT_VERIFIED;
        String email = userInfo.getEmail();
        if (null == email) {
            email = userInfo.getId() + "-google";
            emailStatus = EmailVerificationStatus.DELIVERY_FAILED;
            log.warn("No email address provided by Google! Using (" + email + ") instead");
        }
        return new UserFromAuthProvider(userInfo.getId(), userInfo.getGivenName(), userInfo.getFamilyName(), email, emailStatus, null, null, null);
    } else {
        throw new NoUserException("No user could be created from provider details!");
    }
}
Also used : Credential(com.google.api.client.auth.oauth2.Credential) AuthenticatorSecurityException(uk.ac.cam.cl.dtg.segue.auth.exceptions.AuthenticatorSecurityException) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) UserFromAuthProvider(uk.ac.cam.cl.dtg.isaac.dos.users.UserFromAuthProvider) Oauth2(com.google.api.services.oauth2.Oauth2) CacheBuilder(com.google.common.cache.CacheBuilder) NoUserException(uk.ac.cam.cl.dtg.segue.auth.exceptions.NoUserException) Userinfo(com.google.api.services.oauth2.model.Userinfo) IOException(java.io.IOException) EmailVerificationStatus(uk.ac.cam.cl.dtg.isaac.dos.users.EmailVerificationStatus) JacksonFactory(com.google.api.client.json.jackson2.JacksonFactory)

Aggregations

Credential (com.google.api.client.auth.oauth2.Credential)17 IOException (java.io.IOException)7 OfflineCredentials (com.google.api.ads.common.lib.auth.OfflineCredentials)5 AuthorizationCodeFlow (com.google.api.client.auth.oauth2.AuthorizationCodeFlow)5 AdWordsSession (com.google.api.ads.adwords.lib.client.AdWordsSession)4 MockHttpIntegrationTest (com.google.api.ads.common.lib.testing.MockHttpIntegrationTest)4 ClientParametersAuthentication (com.google.api.client.auth.oauth2.ClientParametersAuthentication)4 AuthorizationCodeInstalledApp (com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp)4 GoogleAuthorizationCodeFlow (com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow)4 Test (org.junit.Test)4 ApiError (com.google.api.ads.adwords.axis.v201809.cm.ApiError)3 ApiException (com.google.api.ads.adwords.axis.v201809.cm.ApiException)3 AdWordsServicesInterface (com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface)3 ConfigurationLoadException (com.google.api.ads.common.lib.conf.ConfigurationLoadException)3 OAuthException (com.google.api.ads.common.lib.exception.OAuthException)3 ValidationException (com.google.api.ads.common.lib.exception.ValidationException)3 AuthorizationCodeTokenRequest (com.google.api.client.auth.oauth2.AuthorizationCodeTokenRequest)3 LocalServerReceiver (com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver)3 GoogleCredential (com.google.api.client.googleapis.auth.oauth2.GoogleCredential)3 GoogleNetHttpTransport (com.google.api.client.googleapis.javanet.GoogleNetHttpTransport)3