Search in sources :

Example 11 with AccessToken

use of com.microsoft.identity.common.internal.providers.oauth2.AccessToken in project spring-vault by spring-projects.

the class GcpIamCredentialsAuthenticationUnitTests method shouldCreateNewGcpIamObjectInstance.

@Test
void shouldCreateNewGcpIamObjectInstance() {
    PrivateKey privateKeyMock = mock(PrivateKey.class);
    ServiceAccountCredentials credential = (ServiceAccountCredentials) ServiceAccountCredentials.newBuilder().setClientEmail("hello@world").setProjectId("foobar").setPrivateKey(privateKeyMock).setPrivateKeyId("key-id").setAccessToken(new AccessToken("foobar", Date.from(Instant.now().plus(1, ChronoUnit.DAYS)))).build();
    GcpIamCredentialsAuthenticationOptions options = GcpIamCredentialsAuthenticationOptions.builder().role("dev-role").credentials(credential).build();
    new GcpIamCredentialsAuthentication(options, this.restTemplate);
}
Also used : PrivateKey(java.security.PrivateKey) AccessToken(com.google.auth.oauth2.AccessToken) ServiceAccountCredentials(com.google.auth.oauth2.ServiceAccountCredentials) Test(org.junit.jupiter.api.Test)

Example 12 with AccessToken

use of com.microsoft.identity.common.internal.providers.oauth2.AccessToken in project spring-vault by spring-projects.

the class GcpIamCredentialsAuthenticationUnitTests method shouldLogin.

@Test
void shouldLogin() {
    this.serverCall = ((request, responseObserver) -> {
        SignJwtResponse signJwtResponse = SignJwtResponse.newBuilder().setSignedJwt("my-jwt").setKeyId("key-id").build();
        responseObserver.onNext(signJwtResponse);
        responseObserver.onCompleted();
    });
    this.mockRest.expect(requestTo("/auth/gcp/login")).andExpect(method(HttpMethod.POST)).andExpect(jsonPath("$.role").value("dev-role")).andExpect(jsonPath("$.jwt").value("my-jwt")).andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body("{" + "\"auth\":{\"client_token\":\"my-token\", \"renewable\": true, \"lease_duration\": 10}" + "}"));
    PrivateKey privateKeyMock = mock(PrivateKey.class);
    ServiceAccountCredentials credential = (ServiceAccountCredentials) ServiceAccountCredentials.newBuilder().setClientEmail("hello@world").setProjectId("foobar").setPrivateKey(privateKeyMock).setPrivateKeyId("key-id").setAccessToken(new AccessToken("foobar", Date.from(Instant.now().plus(1, ChronoUnit.DAYS)))).build();
    GcpIamCredentialsAuthenticationOptions options = GcpIamCredentialsAuthenticationOptions.builder().role("dev-role").credentials(credential).build();
    GcpIamCredentialsAuthentication authentication = new GcpIamCredentialsAuthentication(options, this.restTemplate, FixedTransportChannelProvider.create(GrpcTransportChannel.create(managedChannel)));
    VaultToken login = authentication.login();
    assertThat(login).isInstanceOf(LoginToken.class);
    assertThat(login.getToken()).isEqualTo("my-token");
    LoginToken loginToken = (LoginToken) login;
    assertThat(loginToken.isRenewable()).isTrue();
    assertThat(loginToken.getLeaseDuration()).isEqualTo(Duration.ofSeconds(10));
}
Also used : MockRestResponseCreators.withSuccess(org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess) SignJwtResponse(com.google.cloud.iam.credentials.v1.SignJwtResponse) BeforeEach(org.junit.jupiter.api.BeforeEach) ManagedChannel(io.grpc.ManagedChannel) Date(java.util.Date) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ProtoLiteUtils(io.grpc.protobuf.lite.ProtoLiteUtils) MockRestRequestMatchers.method(org.springframework.test.web.client.match.MockRestRequestMatchers.method) MockRestServiceServer(org.springframework.test.web.client.MockRestServiceServer) InProcessServerBuilder(io.grpc.inprocess.InProcessServerBuilder) PrefixAwareUriTemplateHandler(org.springframework.vault.client.VaultClients.PrefixAwareUriTemplateHandler) FixedTransportChannelProvider(com.google.api.gax.rpc.FixedTransportChannelProvider) ServerCalls.asyncUnaryCall(io.grpc.stub.ServerCalls.asyncUnaryCall) Duration(java.time.Duration) MethodDescriptor(io.grpc.MethodDescriptor) Server(io.grpc.Server) InProcessChannelBuilder(io.grpc.inprocess.InProcessChannelBuilder) RestTemplate(org.springframework.web.client.RestTemplate) MediaType(org.springframework.http.MediaType) HttpMethod(org.springframework.http.HttpMethod) MockRestRequestMatchers.jsonPath(org.springframework.test.web.client.match.MockRestRequestMatchers.jsonPath) IOException(java.io.IOException) Instant(java.time.Instant) MockRestRequestMatchers.requestTo(org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo) Test(org.junit.jupiter.api.Test) GrpcTransportChannel(com.google.api.gax.grpc.GrpcTransportChannel) AfterEach(org.junit.jupiter.api.AfterEach) ChronoUnit(java.time.temporal.ChronoUnit) PrivateKey(java.security.PrivateKey) SignJwtRequest(com.google.cloud.iam.credentials.v1.SignJwtRequest) VaultToken(org.springframework.vault.support.VaultToken) ServerCalls(io.grpc.stub.ServerCalls) ServiceAccountCredentials(com.google.auth.oauth2.ServiceAccountCredentials) ServerServiceDefinition(io.grpc.ServerServiceDefinition) Mockito.mock(org.mockito.Mockito.mock) AccessToken(com.google.auth.oauth2.AccessToken) SignJwtResponse(com.google.cloud.iam.credentials.v1.SignJwtResponse) PrivateKey(java.security.PrivateKey) AccessToken(com.google.auth.oauth2.AccessToken) ServiceAccountCredentials(com.google.auth.oauth2.ServiceAccountCredentials) VaultToken(org.springframework.vault.support.VaultToken) Test(org.junit.jupiter.api.Test)

Example 13 with AccessToken

use of com.microsoft.identity.common.internal.providers.oauth2.AccessToken in project jib by GoogleContainerTools.

the class CredentialRetrieverFactoryTest method setUp.

@Before
public void setUp() throws CredentialHelperUnhandledServerUrlException, CredentialHelperNotFoundException, IOException {
    Mockito.when(mockDockerCredentialHelperFactory.create(Mockito.anyString(), Mockito.any(Path.class), Mockito.anyMap())).thenReturn(mockDockerCredentialHelper);
    Mockito.when(mockDockerCredentialHelper.retrieve()).thenReturn(FAKE_CREDENTIALS);
    Mockito.when(mockGoogleCredentials.getAccessToken()).thenReturn(new AccessToken("my-token", null));
}
Also used : Path(java.nio.file.Path) AccessToken(com.google.auth.oauth2.AccessToken) Before(org.junit.Before)

Example 14 with AccessToken

use of com.microsoft.identity.common.internal.providers.oauth2.AccessToken in project dialogflow-transactions-java by actions-on-google.

the class TransactionsApp method sendOrderUpdate.

private static void sendOrderUpdate(String orderId) throws IOException {
    // Setup service account credentials
    String serviceAccountKeyFileName = "service-account.json";
    // Setup service account credentials
    String serviceAccountFile = TransactionsApp.class.getClassLoader().getResource(serviceAccountKeyFileName).getFile();
    InputStream actionsApiServiceAccount = new FileInputStream(serviceAccountFile);
    ServiceAccountCredentials serviceAccountCredentials = (ServiceAccountCredentials) ServiceAccountCredentials.fromStream(actionsApiServiceAccount).createScoped(Collections.singleton("https://www.googleapis.com/auth/actions.order.developer"));
    AccessToken token = serviceAccountCredentials.refreshAccessToken();
    // Setup request with headers
    HttpPatch request = new HttpPatch("https://actions.googleapis.com/v3/orders/" + orderId);
    request.setHeader("Content-type", "application/json");
    request.setHeader("Authorization", "Bearer " + token.getTokenValue());
    // Create order update
    FieldMask fieldMask = FieldMask.newBuilder().addAllPaths(Arrays.asList("lastUpdateTime", "purchase.status", "purchase.userVisibleStatusLabel")).build();
    OrderUpdateV3 orderUpdate = new OrderUpdateV3().setOrder(new OrderV3().setMerchantOrderId(orderId).setLastUpdateTime(Instant.now().toString()).setPurchase(new PurchaseOrderExtension().setStatus("DELIVERED").setUserVisibleStatusLabel("Order delivered."))).setUpdateMask(FieldMaskUtil.toString(fieldMask)).setReason("Order status was updated to delivered.");
    // Setup JSON body containing order update
    JsonParser parser = new JsonParser();
    JsonObject orderUpdateJson = parser.parse(new Gson().toJson(orderUpdate)).getAsJsonObject();
    JsonObject body = new JsonObject();
    body.add("orderUpdate", orderUpdateJson);
    JsonObject header = new JsonObject();
    header.addProperty("isInSandbox", true);
    body.add("header", header);
    StringEntity entity = new StringEntity(body.toString());
    entity.setContentType(ContentType.APPLICATION_JSON.getMimeType());
    request.setEntity(entity);
    // Make request
    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpResponse response = httpClient.execute(request);
    LOGGER.info(response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) JsonObject(com.google.gson.JsonObject) Gson(com.google.gson.Gson) HttpResponse(org.apache.http.HttpResponse) FileInputStream(java.io.FileInputStream) HttpPatch(org.apache.http.client.methods.HttpPatch) OrderV3(com.google.api.services.actions_fulfillment.v2.model.OrderV3) StringEntity(org.apache.http.entity.StringEntity) AccessToken(com.google.auth.oauth2.AccessToken) OrderUpdateV3(com.google.api.services.actions_fulfillment.v2.model.OrderUpdateV3) HttpClient(org.apache.http.client.HttpClient) ServiceAccountCredentials(com.google.auth.oauth2.ServiceAccountCredentials) FieldMask(com.google.protobuf.FieldMask) PurchaseOrderExtension(com.google.api.services.actions_fulfillment.v2.model.PurchaseOrderExtension) JsonParser(com.google.gson.JsonParser)

Example 15 with AccessToken

use of com.microsoft.identity.common.internal.providers.oauth2.AccessToken in project google-auth-library-java by googleapis.

the class AppEngineCredentials method refreshAccessToken.

/**
 * Refresh the access token by getting it from the App Identity service
 */
@Override
public AccessToken refreshAccessToken() throws IOException {
    if (createScopedRequired()) {
        throw new IOException("AppEngineCredentials requires createScoped call before use.");
    }
    GetAccessTokenResult accessTokenResponse = appIdentityService.getAccessToken(scopes);
    String accessToken = accessTokenResponse.getAccessToken();
    Date expirationTime = accessTokenResponse.getExpirationTime();
    return new AccessToken(accessToken, expirationTime);
}
Also used : AccessToken(com.google.auth.oauth2.AccessToken) IOException(java.io.IOException) GetAccessTokenResult(com.google.appengine.api.appidentity.AppIdentityService.GetAccessTokenResult) Date(java.util.Date)

Aggregations

AccessToken (com.google.auth.oauth2.AccessToken)78 Test (org.junit.Test)44 GoogleCredentials (com.google.auth.oauth2.GoogleCredentials)33 Date (java.util.Date)23 IOException (java.io.IOException)20 AccessToken (io.vertx.ext.auth.oauth2.AccessToken)16 Instant (java.time.Instant)10 Client (javax.ws.rs.client.Client)10 AccessToken (org.glassfish.jersey.client.oauth1.AccessToken)10 ConsumerCredentials (org.glassfish.jersey.client.oauth1.ConsumerCredentials)10 JsonObject (io.vertx.core.json.JsonObject)9 URI (java.net.URI)9 Feature (javax.ws.rs.core.Feature)8 JerseyTest (org.glassfish.jersey.test.JerseyTest)8 MockHttpTransport (com.google.api.client.testing.http.MockHttpTransport)6 ServiceAccountCredentials (com.google.auth.oauth2.ServiceAccountCredentials)6 Credential (io.cdap.cdap.proto.security.Credential)6 InputStreamReader (java.io.InputStreamReader)6 Clock (java.time.Clock)6 WebTarget (javax.ws.rs.client.WebTarget)6