Search in sources :

Example 26 with TokenResponse

use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project google-api-java-client by google.

the class CloudShellCredential method executeRefreshToken.

@Override
protected TokenResponse executeRefreshToken() throws IOException {
    Socket socket = new Socket("localhost", this.getAuthPort());
    socket.setSoTimeout(READ_TIMEOUT_MS);
    TokenResponse token = new TokenResponse();
    try {
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        out.println(GET_AUTH_TOKEN_REQUEST);
        BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        // Ignore the size line
        input.readLine();
        Collection<Object> messageArray = jsonFactory.createJsonParser(input).parseArray(LinkedList.class, Object.class);
        String accessToken = ((List<Object>) messageArray).get(ACCESS_TOKEN_INDEX).toString();
        token.setAccessToken(accessToken);
    } finally {
        socket.close();
    }
    return token;
}
Also used : TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) Socket(java.net.Socket) PrintWriter(java.io.PrintWriter)

Example 27 with TokenResponse

use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project hadoop-connectors by GoogleCloudDataproc.

the class HadoopCredentialsConfigurationTest method metadataServiceIsUsedByDefault.

@Test
public void metadataServiceIsUsedByDefault() throws Exception {
    TokenResponse token = new TokenResponse().setAccessToken("metadata-test-token").setExpiresInSeconds(100L);
    MockHttpTransport transport = mockTransport(jsonDataResponse(token));
    GoogleCredentials credentials = getCredentials(transport);
    credentials.refreshIfExpired();
    assertThat(credentials).isInstanceOf(ComputeEngineCredentials.class);
    assertThat(credentials.getAccessToken().getTokenValue()).isEqualTo("metadata-test-token");
}
Also used : MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) GoogleCredentials(com.google.auth.oauth2.GoogleCredentials) Test(org.junit.Test)

Example 28 with TokenResponse

use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project hadoop-connectors by GoogleCloudDataproc.

the class HadoopCredentialsConfigurationTest method userCredentials_credentialFactory_noNewRefreshToken.

@Test
public void userCredentials_credentialFactory_noNewRefreshToken() throws IOException {
    // GIVEN
    String initialRefreshToken = "FAKE_REFRESH_TOKEN";
    String tokenServerUrl = "http://localhost/token";
    configuration.set(getConfigKey(TOKEN_SERVER_URL_SUFFIX), tokenServerUrl);
    configuration.setEnum(getConfigKey(AUTHENTICATION_TYPE_SUFFIX), AuthenticationType.USER_CREDENTIALS);
    configuration.set(getConfigKey(AUTH_REFRESH_TOKEN_SUFFIX), initialRefreshToken);
    configuration.set(getConfigKey(AUTH_CLIENT_ID_SUFFIX), "FAKE_CLIENT_ID");
    configuration.set(getConfigKey(AUTH_CLIENT_SECRET_SUFFIX), "FAKE_CLIENT_SECRET");
    long expireInSec = 300L;
    String accessTokenAsString = "SlAV32hkKG";
    TokenResponse tokenResponse = new TokenResponse().setAccessToken(accessTokenAsString).setExpiresInSeconds(expireInSec);
    MockHttpTransport transport = mockTransport(jsonDataResponse(tokenResponse));
    // WHEN
    GoogleCredentials credentials = getCredentials(transport);
    credentials.refresh();
    // THEN
    assertThat(credentials).isInstanceOf(UserCredentials.class);
    UserCredentials userCredentials = (UserCredentials) credentials;
    assertThat(userCredentials.getClientId()).isEqualTo("FAKE_CLIENT_ID");
    assertThat(userCredentials.getClientSecret()).isEqualTo("FAKE_CLIENT_SECRET");
    AccessToken accessToken = userCredentials.getAccessToken();
    assertThat(accessToken).isNotNull();
    // To avoid any timebase issue, we test a time range instead
    assertThat(accessToken.getExpirationTime()).isGreaterThan(Date.from(Instant.now().plusSeconds(expireInSec - 10)));
    assertThat(accessToken.getExpirationTime()).isLessThan(Date.from(Instant.now().plusSeconds(expireInSec + 10)));
    String refreshToken = userCredentials.getRefreshToken();
    assertThat(refreshToken).isEqualTo(initialRefreshToken);
}
Also used : MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) AccessToken(com.google.auth.oauth2.AccessToken) GoogleCredentials(com.google.auth.oauth2.GoogleCredentials) UserCredentials(com.google.auth.oauth2.UserCredentials) Test(org.junit.Test)

Example 29 with TokenResponse

use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project SORMAS-Project by hzi-braunschweig.

the class Oidc method requestAccessToken.

public static String requestAccessToken(String tokenEndpoint, String clientId, String clientSecret, List<String> scopes) throws Exception {
    ClientParametersAuthentication clientAuth = new ClientParametersAuthentication(clientId, clientSecret);
    try {
        LOGGER.info(String.format("Requesting access token for client %s at %s with scope: %s", clientId, tokenEndpoint, scopes));
        TokenResponse response = new ClientCredentialsTokenRequest(new NetHttpTransport(), new GsonFactory(), new GenericUrl(tokenEndpoint)).setClientAuthentication(clientAuth).setScopes(scopes).execute();
        String token = response.getAccessToken();
        if (token == null || token.isEmpty()) {
            LOGGER.error("Could not retrieve access token.");
            throw new Exception("Could not retrieve access token.");
        }
        return token;
    } catch (IOException e) {
        LOGGER.error("Unable to connect to Keycloak.", e);
        throw e;
    }
}
Also used : ClientCredentialsTokenRequest(com.google.api.client.auth.oauth2.ClientCredentialsTokenRequest) ClientParametersAuthentication(com.google.api.client.auth.oauth2.ClientParametersAuthentication) GsonFactory(com.google.api.client.json.gson.GsonFactory) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) GenericUrl(com.google.api.client.http.GenericUrl) IOException(java.io.IOException) IOException(java.io.IOException)

Example 30 with TokenResponse

use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project isaac-api by isaacphysics.

the class TwitterAuthenticator method exchangeCode.

@Override
public String exchangeCode(final String authorizationCode) throws CodeExchangeException {
    try {
        AccessToken accessToken = twitter.getOAuthAccessToken(authorizationCode);
        TokenResponse tokenResponse = new TokenResponse();
        tokenResponse.setAccessToken(accessToken.getToken());
        tokenResponse.setRefreshToken(accessToken.getTokenSecret());
        tokenResponse.setExpiresInSeconds(Long.MAX_VALUE);
        Builder builder = new AuthorizationCodeFlow.Builder(BearerToken.authorizationHeaderAccessMethod(), httpTransport, jsonFactory, new GenericUrl(TOKEN_EXCHANGE_URL), new ClientParametersAuthentication(clientId, clientSecret), clientId, AUTH_URL);
        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 | TwitterException | IllegalStateException e) {
        log.error("An error occurred during code exchange: " + e);
        throw new CodeExchangeException();
    }
}
Also used : Credential(com.google.api.client.auth.oauth2.Credential) ConfigurationBuilder(twitter4j.conf.ConfigurationBuilder) Builder(com.google.api.client.auth.oauth2.AuthorizationCodeFlow.Builder) GenericUrl(com.google.api.client.http.GenericUrl) IOException(java.io.IOException) AuthorizationCodeFlow(com.google.api.client.auth.oauth2.AuthorizationCodeFlow) ClientParametersAuthentication(com.google.api.client.auth.oauth2.ClientParametersAuthentication) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) AccessToken(twitter4j.auth.AccessToken) CodeExchangeException(uk.ac.cam.cl.dtg.segue.auth.exceptions.CodeExchangeException) TwitterException(twitter4j.TwitterException)

Aggregations

TokenResponse (com.google.api.client.auth.oauth2.TokenResponse)48 IOException (java.io.IOException)23 GenericUrl (com.google.api.client.http.GenericUrl)22 Credential (com.google.api.client.auth.oauth2.Credential)20 ClientParametersAuthentication (com.google.api.client.auth.oauth2.ClientParametersAuthentication)16 AuthorizationCodeFlow (com.google.api.client.auth.oauth2.AuthorizationCodeFlow)15 Map (java.util.Map)13 NetHttpTransport (com.google.api.client.http.javanet.NetHttpTransport)12 TokenResponse (com.microsoft.identity.common.internal.providers.oauth2.TokenResponse)11 BearerToken (com.google.api.client.auth.oauth2.BearerToken)9 TokenResult (com.microsoft.identity.common.internal.providers.oauth2.TokenResult)8 Logger (org.slf4j.Logger)8 LoggerFactory (org.slf4j.LoggerFactory)8 Test (org.junit.Test)7 URL (java.net.URL)6 HashMap (java.util.HashMap)6 List (java.util.List)6 Timed (com.codahale.metrics.annotation.Timed)5 AuthorizationCodeRequestUrl (com.google.api.client.auth.oauth2.AuthorizationCodeRequestUrl)5 Collections (java.util.Collections)5