use of com.microsoft.identity.common.internal.providers.oauth2.AccessToken in project terra-cli by DataBiosphere.
the class GoogleOauth method doLoginAndConsent.
/**
* Do the Google OAuth2 flow for the specified userId. If there is no existing, unexpired
* credential for this userId, this method will require browser window to ask for consent to
* access the specified scopes. This browser window is either launched automatically or the URL
* printed to stdout, depending on the boolean flag.
*
* @param scopes list of scopes to request from the user
* @param clientSecretFile stream to the client secret file
* @param dataStoreDir directory in which to persist the local credential store
* @param launchBrowserAutomatically true to launch a browser automatically and listen on a local
* server for the token response, false to print the url to stdout and ask the user to
* copy/paste the token response to stdin
* @param loginLandingPage URL of the page to load in the browser upon completion of login
* @return credentials object for the user
*/
public static UserCredentials doLoginAndConsent(List<String> scopes, InputStream clientSecretFile, File dataStoreDir, boolean launchBrowserAutomatically, String loginLandingPage) throws IOException, GeneralSecurityException {
// load client_secret.json file
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(clientSecretFile, StandardCharsets.UTF_8));
// setup the Google OAuth2 flow
GoogleAuthorizationCodeFlow flow = getOAuth2Flow(scopes, clientSecrets, dataStoreDir);
// exchange an authorization code for a refresh token
Credential credential;
if (launchBrowserAutomatically) {
// launch a browser window on this machine and listen on a local port for the token response
LocalServerReceiver receiver = new LocalServerReceiver.Builder().setLandingPages(loginLandingPage, loginLandingPage).build();
credential = new AuthorizationCodeInstalledApp(flow, receiver).authorize(CREDENTIAL_STORE_KEY);
} else {
// print the url to stdout and ask the user to copy/paste the token response to stdin
credential = new AuthorizationCodeInstalledApp(flow, new StdinReceiver(), new NoLaunchBrowser()).authorize(CREDENTIAL_STORE_KEY);
}
// OAuth2 Credentials representing a user's identity and consent
UserCredentials credentials = UserCredentials.newBuilder().setClientId(clientSecrets.getDetails().getClientId()).setClientSecret(clientSecrets.getDetails().getClientSecret()).setRefreshToken(credential.getRefreshToken()).setAccessToken(new AccessToken(credential.getAccessToken(), new Date(credential.getExpirationTimeMilliseconds()))).build();
// only try to refresh if the refresh token is set
if (credentials.getRefreshToken() == null || credentials.getRefreshToken().isEmpty()) {
logger.info("Refresh token is not set. This is expected when testing, not during normal operation.");
} else {
credentials.refresh();
}
return credentials;
}
use of com.microsoft.identity.common.internal.providers.oauth2.AccessToken in project jade-data-repo by DataBiosphere.
the class KubernetesClientUtils method buildKubernetesClientObject.
private static CoreV1Api buildKubernetesClientObject(String clusterName, String region, String project) throws Exception {
// call the fetchGKECrednetials script that uses gcloud to generate the kubeconfig file
List<String> scriptArgs = new ArrayList<>();
scriptArgs.add("tools/fetchGKECredentials.sh");
scriptArgs.add(clusterName);
scriptArgs.add(region);
scriptArgs.add(project);
executeCommand("sh", scriptArgs);
// path to kubeconfig file, that was just created/updated by gcloud get-credentials above
String kubeConfigPath = System.getProperty("user.home") + "/.kube/config";
// load the kubeconfig object from the file
InputStreamReader filereader = new InputStreamReader(new FileInputStream(kubeConfigPath), Charset.forName("UTF-8"));
KubeConfig kubeConfig = KubeConfig.loadKubeConfig(filereader);
// get a refreshed SA access token and its expiration time
AccessToken accessToken = getApplicationDefaultAccessToken();
Instant tokenExpiration = accessToken.getExpirationTime().toInstant();
String expiryUTC = tokenExpiration.atZone(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT);
// USERS: build list of one user, the SA
LinkedHashMap<String, Object> authConfigSA = new LinkedHashMap<>();
authConfigSA.put("access-token", accessToken.getTokenValue());
authConfigSA.put("expiry", expiryUTC);
LinkedHashMap<String, Object> authProviderSA = new LinkedHashMap<>();
authProviderSA.put("name", "gcp");
authProviderSA.put("config", authConfigSA);
LinkedHashMap<String, Object> userSA = new LinkedHashMap<>();
userSA.put("auth-provider", authProviderSA);
LinkedHashMap<String, Object> userWrapperSA = new LinkedHashMap<>();
userWrapperSA.put("name", clusterName);
userWrapperSA.put("user", userSA);
ArrayList<Object> usersList = new ArrayList<>();
usersList.add(userWrapperSA);
// CONTEXTS: build list of one context, the specified cluster
LinkedHashMap<String, Object> context = new LinkedHashMap<>();
context.put("cluster", clusterName);
// when is the user ever different from the cluster name?
context.put("user", clusterName);
LinkedHashMap<String, Object> contextWrapper = new LinkedHashMap<>();
contextWrapper.put("name", clusterName);
contextWrapper.put("context", context);
ArrayList<Object> contextsList = new ArrayList<>();
contextsList.add(contextWrapper);
// CLUSTERS: use the cluster list read in from the kubeconfig file, because I can't figure out how to get the
// certificate-authority-data and server address for the cluster via the Java client library, only with gcloud
ArrayList<Object> clusters = kubeConfig.getClusters();
// build the config object, replacing the contexts and users lists from the kubeconfig file with the ones
// constructed programmatically above
kubeConfig = new KubeConfig(contextsList, clusters, usersList);
kubeConfig.setContext(clusterName);
// build the client object from the config
ApiClient client = ClientBuilder.kubeconfig(kubeConfig).build();
// set the global default client to the one created above because the CoreV1Api constructor gets the client
// object from the global configuration
Configuration.setDefaultApiClient(client);
return new CoreV1Api();
}
use of com.microsoft.identity.common.internal.providers.oauth2.AccessToken in project jade-data-repo by DataBiosphere.
the class DataRepoFixtures method getStorage.
public Storage getStorage(String token) {
GoogleCredentials googleCredentials = GoogleCredentials.create(new AccessToken(token, null));
StorageOptions storageOptions = StorageOptions.newBuilder().setCredentials(googleCredentials).build();
return storageOptions.getService();
}
use of com.microsoft.identity.common.internal.providers.oauth2.AccessToken in project jersey by eclipse-ee4j.
the class OAuthClientServerTest method testRequestSigningWithExceedingCache.
/**
* Tests configuration of the nonce cache on the server side.
*/
@Test
public void testRequestSigningWithExceedingCache() {
final Feature filterFeature = OAuth1ClientSupport.builder(new ConsumerCredentials(CONSUMER_KEY, SECRET_CONSUMER_KEY)).feature().accessToken(new AccessToken(PROMETHEUS_TOKEN, PROMETHEUS_SECRET)).build();
final Client client = ClientBuilder.newBuilder().register(filterFeature).build();
final URI resourceUri = UriBuilder.fromUri(getBaseUri()).path("resource").build();
final WebTarget target = client.target(resourceUri);
Response response;
for (int i = 0; i < 20; i++) {
System.out.println("request: " + i);
response = target.request().get();
assertEquals(200, response.getStatus());
assertEquals("prometheus", response.readEntity(String.class));
i++;
response = target.path("admin").request().get();
assertEquals(200, response.getStatus());
assertEquals(true, response.readEntity(boolean.class));
}
// now the nonce cache is full
response = target.request().get();
assertEquals(401, response.getStatus());
}
use of com.microsoft.identity.common.internal.providers.oauth2.AccessToken in project jersey by eclipse-ee4j.
the class OauthClientAuthorizationFlowTest method testOAuthClientFeature.
/**
* Tests mainly the client functionality. The test client registers
* {@link org.glassfish.jersey.client.oauth1.OAuth1ClientFilter} and uses the filter only to sign requests. So, it does not
* use the filter to perform authorization flow. However, each request that this test performs is actually a request used
* during the authorization flow.
* <p/>
* The server side of this test extracts header authorization values and tests that signatures are
* correct for each request type.
*/
@Test
public void testOAuthClientFeature() {
final URI baseUri = getBaseUri();
// baseline for requests
final OAuth1Builder oAuth1Builder = OAuth1ClientSupport.builder(new ConsumerCredentials("dpf43f3p2l4k3l03", "kd94hf93k423kf44")).timestamp("1191242090").nonce("hsu94j3884jdopsl").signatureMethod(PlaintextMethod.NAME).version("1.0");
final Feature feature = oAuth1Builder.feature().build();
final Client client = client();
client.register(LoggingFeature.class);
final WebTarget target = client.target(baseUri);
// simulate request for Request Token (temporary credentials)
String responseEntity = target.path("request_token").register(feature).request().post(Entity.entity("entity", MediaType.TEXT_PLAIN_TYPE), String.class);
assertEquals(responseEntity, "oauth_token=hh5s93j4hdidpola&oauth_token_secret=hdhd0244k9j7ao03");
final Feature feature2 = oAuth1Builder.timestamp("1191242092").nonce("dji430splmx33448").feature().accessToken(new AccessToken("hh5s93j4hdidpola", "hdhd0244k9j7ao03")).build();
// simulate request for Access Token
responseEntity = target.path("access_token").register(feature2).request().post(Entity.entity("entity", MediaType.TEXT_PLAIN_TYPE), String.class);
assertEquals(responseEntity, "oauth_token=nnch734d00sl2jdk&oauth_token_secret=pfkkdhi9sl3r4s00");
final Feature feature3 = oAuth1Builder.nonce("kllo9940pd9333jh").signatureMethod("HMAC-SHA1").timestamp("1191242096").feature().accessToken(new AccessToken("nnch734d00sl2jdk", "pfkkdhi9sl3r4s00")).build();
// based on Access Token
responseEntity = target.path("/photos").register(feature3).queryParam("file", "vacation.jpg").queryParam("size", "original").request().get(String.class);
assertEquals(responseEntity, "PHOTO");
}
Aggregations