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);
}
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;
}
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());
}
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);
}
}
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!");
}
}
Aggregations