Search in sources :

Example 41 with AccessToken

use of com.microsoft.identity.common.internal.providers.oauth2.AccessToken in project workbench by all-of-us.

the class DelegatedUserCredentials method refreshAccessToken.

@Override
public AccessToken refreshAccessToken() throws IOException {
    // The first step is to call the IamCredentials API to generate a signed JWT with the
    // appropriate claims. This call is authorized with application default credentials (ADCs). The
    // ADC service account may be different from `serviceAccountEmail` if the ADC account has the
    // roles/iam.serviceAccountTokenCreator role on the `serviceAccountEmail` account.
    SignJwtRequest jwtRequest = SignJwtRequest.newBuilder().setName(String.format(SERVICE_ACCOUNT_NAME_FORMAT, serviceAccountEmail)).setPayload(JSON_FACTORY.toString(createJwtPayload())).build();
    String jwt = credentialsClient.signJwt(jwtRequest).getSignedJwt();
    // With the signed JWT in hand, we call Google's OAuth2 token server to exchange the JWT for
    // an access token.
    TokenRequest tokenRequest = new TokenRequest(httpTransport, JSON_FACTORY, new GenericUrl(GoogleOAuthConstants.TOKEN_SERVER_URL), JWT_BEARER_GRANT_TYPE);
    tokenRequest.put("assertion", jwt);
    TokenResponse tokenResponse = tokenRequest.execute();
    return new AccessToken(tokenResponse.getAccessToken(), Date.from(Instant.now(clock).plusSeconds(tokenResponse.getExpiresInSeconds())));
}
Also used : TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) AccessToken(com.google.auth.oauth2.AccessToken) TokenRequest(com.google.api.client.auth.oauth2.TokenRequest) SignJwtRequest(com.google.cloud.iam.credentials.v1.SignJwtRequest) GenericUrl(com.google.api.client.http.GenericUrl)

Example 42 with AccessToken

use of com.microsoft.identity.common.internal.providers.oauth2.AccessToken in project curiostack by curioswitch.

the class AbstractAccessTokenProvider method refresh.

private CompletableFuture<AccessToken> refresh(Type type) {
    return fetchToken(type).handle((msg, t) -> {
        if (t != null) {
            throw new IllegalStateException("Failed to refresh GCP access token.", t);
        }
        final TokenResponse response;
        try {
            response = OBJECT_MAPPER.readValue(msg.content().array(), TokenResponse.class);
        } catch (IOException e) {
            throw new UncheckedIOException("Error parsing token refresh response.", e);
        }
        long expiresAtMilliseconds = clock.millis() + TimeUnit.SECONDS.toMillis(response.expiresIn());
        return new AccessToken(type == Type.ID_TOKEN ? response.idToken() : response.accessToken(), new Date(expiresAtMilliseconds));
    });
}
Also used : AccessToken(com.google.auth.oauth2.AccessToken) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) Date(java.util.Date)

Example 43 with AccessToken

use of com.microsoft.identity.common.internal.providers.oauth2.AccessToken in project cdap by caskdata.

the class ComputeEngineCredentials method getAccessTokenRemotely.

private AccessToken getAccessTokenRemotely(String endPoint) throws IOException {
    URL url = new URL(endPoint);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    if (connection instanceof HttpsURLConnection) {
        // TODO (CDAP-18047) enable ssl verification
        disableVerifySSL(((HttpsURLConnection) connection));
    }
    connection.connect();
    try (Reader reader = new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8)) {
        if (connection.getResponseCode() != HttpResponseStatus.OK.code()) {
            throw new IOException(CharStreams.toString(reader));
        }
        GenericData token = GSON.fromJson(reader, GenericData.class);
        if (!token.containsKey(ACCESS_TOKEN_KEY) || !token.containsKey(EXPIRES_IN_KEY)) {
            throw new IOException("Received invalid token");
        }
        String key = token.get(ACCESS_TOKEN_KEY).toString();
        Double expiration = Double.parseDouble(token.get(EXPIRES_IN_KEY).toString());
        long expiresAtMilliseconds = System.currentTimeMillis() + expiration.longValue() * 1000;
        return new AccessToken(key, new Date(expiresAtMilliseconds));
    } finally {
        connection.disconnect();
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) InputStreamReader(java.io.InputStreamReader) AccessToken(com.google.auth.oauth2.AccessToken) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) IOException(java.io.IOException) GenericData(com.google.api.client.util.GenericData) URL(java.net.URL) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) Date(java.util.Date)

Example 44 with AccessToken

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

the class GoogleSecretManagerV1AccessStrategy method checkRemotePermissions.

@Override
public Boolean checkRemotePermissions() {
    CloudResourceManager service = null;
    try {
        AccessToken accessToken = new AccessToken(getAccessToken(), null);
        GoogleCredentials credential = new GoogleCredentials(accessToken);
        HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credential);
        service = new CloudResourceManager.Builder(GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), requestInitializer).setApplicationName(APPLICATION_NAME).build();
        List<String> permissionsList = Arrays.asList(ACCESS_SECRET_PERMISSION);
        TestIamPermissionsRequest requestBody = new TestIamPermissionsRequest().setPermissions(permissionsList);
        TestIamPermissionsResponse testIamPermissionsResponse = service.projects().testIamPermissions(getProjectId(), requestBody).execute();
        if (testIamPermissionsResponse.getPermissions() != null && testIamPermissionsResponse.size() >= 1) {
            return Boolean.TRUE;
        } else {
            logger.warn("Access token has no permissions to access secrets in project");
            return Boolean.FALSE;
        }
    } catch (Exception e) {
        logger.info("Unable to check token permissions", e);
        return Boolean.FALSE;
    }
}
Also used : HttpCredentialsAdapter(com.google.auth.http.HttpCredentialsAdapter) CloudResourceManager(com.google.api.services.cloudresourcemanager.CloudResourceManager) TestIamPermissionsRequest(com.google.api.services.cloudresourcemanager.model.TestIamPermissionsRequest) TestIamPermissionsResponse(com.google.api.services.cloudresourcemanager.model.TestIamPermissionsResponse) AccessToken(com.google.auth.oauth2.AccessToken) GoogleCredentials(com.google.auth.oauth2.GoogleCredentials) HttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer) IOException(java.io.IOException)

Example 45 with AccessToken

use of com.microsoft.identity.common.internal.providers.oauth2.AccessToken in project cdap by caskdata.

the class GCPRemoteAuthenticatorTest method testRemoteAuthenticatorRefreshesNullAccessToken.

@Test
public void testRemoteAuthenticatorRefreshesNullAccessToken() throws Exception {
    String accessTokenValue = "access-token";
    // This is just an arbitrary fixed point in time.
    Instant fixedInstant = Instant.ofEpochSecond(1646358109);
    Clock fixedClock = Clock.fixed(fixedInstant, ZoneId.systemDefault());
    GoogleCredentials mockGoogleCredentials = mock(GoogleCredentials.class);
    AccessToken accessToken = new AccessToken(accessTokenValue, Date.from(fixedInstant.plus(Duration.ofHours(1))));
    when(mockGoogleCredentials.refreshAccessToken()).thenReturn(accessToken);
    GCPRemoteAuthenticator gcpRemoteAuthenticator = new GCPRemoteAuthenticator(mockGoogleCredentials, fixedClock, null);
    // Verify expected credential value and that refresh was called exactly once.
    Credential credential = gcpRemoteAuthenticator.getCredentials();
    Assert.assertEquals(accessTokenValue, credential.getValue());
    verify(mockGoogleCredentials, times(1)).refreshAccessToken();
}
Also used : Credential(io.cdap.cdap.proto.security.Credential) AccessToken(com.google.auth.oauth2.AccessToken) Instant(java.time.Instant) GoogleCredentials(com.google.auth.oauth2.GoogleCredentials) Clock(java.time.Clock) Test(org.junit.Test)

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