use of com.microsoft.identity.common.internal.providers.oauth2.AccessToken in project artifact-registry-maven-tools by GoogleCloudPlatform.
the class GcloudCredentials method getGcloudAccessToken.
private static AccessToken getGcloudAccessToken() throws IOException {
ProcessBuilder processBuilder = new ProcessBuilder();
String gcloud = gCloudCommand();
processBuilder.command(gcloud, "config", "config-helper", "--format=json(credential)");
Process process = processBuilder.start();
try {
int exitCode = process.waitFor();
String stdOut = readStreamToString(process.getInputStream());
if (exitCode != 0) {
String stdErr = readStreamToString(process.getErrorStream());
throw new IOException(String.format("gcloud exited with status: %d\nOutput:\n%s\nError Output:\n%s\n", exitCode, stdOut, stdErr));
}
GenericData result = JSON_FACTORY.fromString(stdOut, GenericData.class);
Map credential = (Map) result.get("credential");
if (credential == null) {
throw new IOException("No credential returned from gcloud");
}
if (!credential.containsKey(KEY_ACCESS_TOKEN) || !credential.containsKey(KEY_TOKEN_EXPIRY)) {
throw new IOException("Malformed response from gcloud");
}
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date expiry = df.parse((String) credential.get(KEY_TOKEN_EXPIRY));
return new AccessToken((String) credential.get(KEY_ACCESS_TOKEN), expiry);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException(e);
} catch (ParseException e) {
throw new IOException("Failed to parse timestamp from gcloud output", e);
}
}
use of com.microsoft.identity.common.internal.providers.oauth2.AccessToken in project artifact-registry-maven-tools by GoogleCloudPlatform.
the class ArtifactRegistryWagonTest method testAuthenticatedGet.
@Test
public void testAuthenticatedGet() throws Exception {
MockHttpTransport transport = new MockHttpTransport.Builder().setLowLevelHttpResponse(new MockLowLevelHttpResponse().setContent("test content")).build();
ArtifactRegistryWagon wagon = new ArtifactRegistryWagon();
wagon.setCredentialProvider(() -> GoogleCredentials.create(new AccessToken("test-access-token", Date.from(Instant.now().plusSeconds(1000)))));
wagon.setHttpTransportFactory(() -> transport);
wagon.connect(new Repository("my-repo", REPO_URL));
File f = FileTestUtils.createUniqueFile("my/artifact/dir", "test");
wagon.get("my/resource", f);
assertFileContains(f, "test content");
String authHeader = transport.getLowLevelHttpRequest().getFirstHeaderValue("Authorization");
Assert.assertEquals("Bearer test-access-token", authHeader);
Assert.assertEquals("https://maven.pkg.dev/my-project/my-repo/my/resource", transport.getLowLevelHttpRequest().getUrl());
}
use of com.microsoft.identity.common.internal.providers.oauth2.AccessToken in project artifact-registry-maven-tools by GoogleCloudPlatform.
the class ArtifactRegistryWagonTest method testHeadNotFound.
@Test
public void testHeadNotFound() throws Exception {
MockHttpTransport transport = failingTransportWithStatus(HttpStatusCodes.STATUS_CODE_NOT_FOUND);
ArtifactRegistryWagon wagon = new ArtifactRegistryWagon();
wagon.setCredentialProvider(() -> GoogleCredentials.create(new AccessToken("test-access-token", Date.from(Instant.now().plusSeconds(1000)))));
wagon.setHttpTransportFactory(() -> transport);
wagon.connect(new Repository("my-repo", REPO_URL));
Assert.assertFalse(wagon.resourceExists("my/resource"));
}
use of com.microsoft.identity.common.internal.providers.oauth2.AccessToken in project jersey by eclipse-ee4j.
the class App method main.
/**
* Main method that creates a {@link Client client} and initializes the OAuth support with
* configuration needed to connect to the Twitter and retrieve statuses.
* <p/>
* Execute this method to demo
*
* @param args Command line arguments.
* @throws Exception Thrown when error occurs.
*/
public static void main(final String[] args) throws Exception {
// retrieve consumer key/secret and token/secret from the property file
// or system properties
loadSettings();
final ConsumerCredentials consumerCredentials = new ConsumerCredentials(PROPERTIES.getProperty(PROPERTY_CONSUMER_KEY), PROPERTIES.getProperty(PROPERTY_CONSUMER_SECRET));
final Feature filterFeature;
if (PROPERTIES.getProperty(PROPERTY_TOKEN) == null) {
// we do not have Access Token yet. Let's perfom the Authorization Flow first,
// let the user approve our app and get Access Token.
final OAuth1AuthorizationFlow authFlow = OAuth1ClientSupport.builder(consumerCredentials).authorizationFlow("https://api.twitter.com/oauth/request_token", "https://api.twitter.com/oauth/access_token", "https://api.twitter.com/oauth/authorize").build();
final String authorizationUri = authFlow.start();
System.out.println("Enter the following URI into a web browser and authorize me:");
System.out.println(authorizationUri);
System.out.print("Enter the authorization code: ");
final String verifier;
try {
verifier = IN.readLine();
} catch (final IOException ex) {
throw new RuntimeException(ex);
}
final AccessToken accessToken = authFlow.finish(verifier);
// store access token for next application execution
PROPERTIES.setProperty(PROPERTY_TOKEN, accessToken.getToken());
PROPERTIES.setProperty(PROPERTY_TOKEN_SECRET, accessToken.getAccessTokenSecret());
// get the feature that will configure the client with consumer credentials and
// received access token
filterFeature = authFlow.getOAuth1Feature();
} else {
final AccessToken storedToken = new AccessToken(PROPERTIES.getProperty(PROPERTY_TOKEN), PROPERTIES.getProperty(PROPERTY_TOKEN_SECRET));
// build a new feature from the stored consumer credentials and access token
filterFeature = OAuth1ClientSupport.builder(consumerCredentials).feature().accessToken(storedToken).build();
}
// create a new Jersey client and register filter feature that will add OAuth signatures and
// JacksonFeature that will process returned JSON data.
final Client client = ClientBuilder.newBuilder().register(filterFeature).register(JacksonFeature.class).build();
// make requests to protected resources
// (no need to care about the OAuth signatures)
final Response response = client.target(FRIENDS_TIMELINE_URI).request().get();
if (response.getStatus() != 200) {
String errorEntity = null;
if (response.hasEntity()) {
errorEntity = response.readEntity(String.class);
}
throw new RuntimeException("Request to Twitter was not successful. Response code: " + response.getStatus() + ", reason: " + response.getStatusInfo().getReasonPhrase() + ", entity: " + errorEntity);
}
// persist the current consumer key/secret and token/secret for future use
storeSettings();
final List<Status> statuses = response.readEntity(new GenericType<List<Status>>() {
});
System.out.println("Tweets:\n");
for (final Status s : statuses) {
System.out.println(s.getText());
System.out.println("[posted by " + s.getUser().getName() + " at " + s.getCreatedAt() + "]");
}
}
use of com.microsoft.identity.common.internal.providers.oauth2.AccessToken in project jersey by eclipse-ee4j.
the class OAuthClientServerTest method testRequestSigning.
/**
* Tests {@link org.glassfish.jersey.client.oauth1.OAuth1ClientFilter} already configured with Access Token for signature
* purposes only.
*/
@Test
public void testRequestSigning() {
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 < 15; 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));
}
}
Aggregations