Search in sources :

Example 16 with AccessToken

use of co.cask.cdap.security.authentication.client.AccessToken in project cdap by caskdata.

the class RESTClientTest method testPostForbidden.

@Test(expected = UnauthorizedException.class)
public void testPostForbidden() throws Exception {
    URL url = getBaseURI().resolve("/api/testPostForbidden").toURL();
    HttpRequest request = HttpRequest.post(url).build();
    restClient.execute(request, new AccessToken("Unknown", 82000L, "Bearer"));
}
Also used : HttpRequest(co.cask.common.http.HttpRequest) AccessToken(co.cask.cdap.security.authentication.client.AccessToken) URL(java.net.URL) Test(org.junit.Test)

Example 17 with AccessToken

use of co.cask.cdap.security.authentication.client.AccessToken in project cdap by caskdata.

the class RESTClientTest method testGetSuccessWithAccessToken.

@Test
public void testGetSuccessWithAccessToken() throws Exception {
    URL url = getBaseURI().resolve("/api/testGetAuth").toURL();
    HttpRequest request = HttpRequest.get(url).build();
    HttpResponse response = restClient.execute(request, new AccessToken(ACCESS_TOKEN, 82000L, "Bearer"));
    verifyResponse(response, only(200), any(), only("Access token received: " + ACCESS_TOKEN));
}
Also used : HttpRequest(co.cask.common.http.HttpRequest) AccessToken(co.cask.cdap.security.authentication.client.AccessToken) HttpResponse(co.cask.common.http.HttpResponse) URL(java.net.URL) Test(org.junit.Test)

Example 18 with AccessToken

use of co.cask.cdap.security.authentication.client.AccessToken in project cdap by caskdata.

the class StreamClient method getEvents.

/**
   * Reads events from a stream
   *
   * @param streamId ID of the stream
   * @param start Timestamp in milliseconds or now-xs format to start reading event from (inclusive)
   * @param end Timestamp in milliseconds or now-xs format for the last event to read (exclusive)
   * @param limit Maximum number of events to read
   * @param callback Callback to invoke for each stream event read. If the callback function returns {@code false}
   *                 upon invocation, it will stops the reading
   * @throws IOException If fails to read from stream
   * @throws StreamNotFoundException If the given stream does not exists
   */
public void getEvents(StreamId streamId, String start, String end, int limit, Function<? super StreamEvent, Boolean> callback) throws IOException, StreamNotFoundException, UnauthenticatedException {
    long startTime = TimeMathParser.parseTime(start, TimeUnit.MILLISECONDS);
    long endTime = TimeMathParser.parseTime(end, TimeUnit.MILLISECONDS);
    URL url = config.resolveNamespacedURLV3(streamId.getParent(), String.format("streams/%s/events?start=%d&end=%d&limit=%d", streamId.getStream(), startTime, endTime, limit));
    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
    AccessToken accessToken = config.getAccessToken();
    if (accessToken != null) {
        urlConn.setRequestProperty(HttpHeaders.AUTHORIZATION, accessToken.getTokenType() + " " + accessToken.getValue());
    }
    if (urlConn instanceof HttpsURLConnection && !config.isVerifySSLCert()) {
        try {
            HttpRequests.disableCertCheck((HttpsURLConnection) urlConn);
        } catch (Exception e) {
        // TODO: Log "Got exception while disabling SSL certificate check for request.getURL()"
        }
    }
    try {
        if (urlConn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
            throw new UnauthenticatedException("Unauthorized status code received from the server.");
        }
        if (urlConn.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) {
            throw new StreamNotFoundException(streamId);
        }
        if (urlConn.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) {
            return;
        }
        // The response is an array of stream event object
        InputStream inputStream = urlConn.getInputStream();
        JsonReader jsonReader = new JsonReader(new InputStreamReader(inputStream, Charsets.UTF_8));
        jsonReader.beginArray();
        while (jsonReader.peek() != JsonToken.END_ARRAY) {
            Boolean result = callback.apply(GSON.<StreamEvent>fromJson(jsonReader, StreamEvent.class));
            if (result == null || !result) {
                break;
            }
        }
        drain(inputStream);
    // No need to close reader, the urlConn.disconnect in finally will close all underlying streams
    } finally {
        urlConn.disconnect();
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) StreamEvent(co.cask.cdap.api.flow.flowlet.StreamEvent) URL(java.net.URL) IOException(java.io.IOException) UnauthenticatedException(co.cask.cdap.common.UnauthenticatedException) StreamNotFoundException(co.cask.cdap.common.StreamNotFoundException) BadRequestException(co.cask.cdap.common.BadRequestException) UnauthorizedException(co.cask.cdap.security.spi.authorization.UnauthorizedException) HttpURLConnection(java.net.HttpURLConnection) UnauthenticatedException(co.cask.cdap.common.UnauthenticatedException) AccessToken(co.cask.cdap.security.authentication.client.AccessToken) StreamNotFoundException(co.cask.cdap.common.StreamNotFoundException) JsonReader(com.google.gson.stream.JsonReader) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Example 19 with AccessToken

use of co.cask.cdap.security.authentication.client.AccessToken in project cdap by caskdata.

the class UpgradeTool method getClientConfig.

private static ClientConfig getClientConfig(CommandLine commandLine) throws IOException {
    String uriStr = commandLine.hasOption("u") ? commandLine.getOptionValue("u") : "localhost:11015";
    if (!uriStr.contains("://")) {
        uriStr = "http://" + uriStr;
    }
    URI uri = URI.create(uriStr);
    String hostname = uri.getHost();
    int port = uri.getPort();
    boolean sslEnabled = "https".equals(uri.getScheme());
    ConnectionConfig connectionConfig = ConnectionConfig.builder().setHostname(hostname).setPort(port).setSSLEnabled(sslEnabled).build();
    int readTimeout = commandLine.hasOption("t") ? Integer.parseInt(commandLine.getOptionValue("t")) : DEFAULT_READ_TIMEOUT_MILLIS;
    ClientConfig.Builder clientConfigBuilder = ClientConfig.builder().setDefaultReadTimeout(readTimeout).setConnectionConfig(connectionConfig);
    if (commandLine.hasOption("a")) {
        String tokenFilePath = commandLine.getOptionValue("a");
        File tokenFile = new File(tokenFilePath);
        if (!tokenFile.exists()) {
            throw new IllegalArgumentException("Access token file " + tokenFilePath + " does not exist.");
        }
        if (!tokenFile.isFile()) {
            throw new IllegalArgumentException("Access token file " + tokenFilePath + " is not a file.");
        }
        String tokenValue = new String(Files.readAllBytes(tokenFile.toPath()), StandardCharsets.UTF_8).trim();
        AccessToken accessToken = new AccessToken(tokenValue, 82000L, "Bearer");
        clientConfigBuilder.setAccessToken(accessToken);
    }
    return clientConfigBuilder.build();
}
Also used : AccessToken(co.cask.cdap.security.authentication.client.AccessToken) ClientConfig(co.cask.cdap.client.config.ClientConfig) URI(java.net.URI) File(java.io.File) ConnectionConfig(co.cask.cdap.client.config.ConnectionConfig)

Example 20 with AccessToken

use of co.cask.cdap.security.authentication.client.AccessToken in project cdap-ingest by caskdata.

the class RestStreamClientTest method testNotAuthorizedUnknownTokenSetTTL.

@Test
public void testNotAuthorizedUnknownTokenSetTTL() throws IOException {
    AuthenticationClient authClient = Mockito.mock(AuthenticationClient.class);
    AccessToken accessToken = Mockito.mock(AccessToken.class);
    Mockito.when(authClient.getAccessToken()).thenReturn(accessToken);
    Mockito.when(accessToken.getValue()).thenReturn("test");
    Mockito.when(accessToken.getTokenType()).thenReturn("Bearer");
    createClient(authClient);
    try {
        streamClient.setTTL(TestUtils.AUTH_STREAM_NAME, STREAM_TTL);
        Assert.fail("Expected HttpFailureException");
    } catch (HttpFailureException e) {
        Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, e.getStatusCode());
    }
}
Also used : HttpFailureException(co.cask.common.http.exception.HttpFailureException) AccessToken(co.cask.cdap.security.authentication.client.AccessToken) AuthenticationClient(co.cask.cdap.security.authentication.client.AuthenticationClient) Test(org.junit.Test)

Aggregations

AccessToken (co.cask.cdap.security.authentication.client.AccessToken)34 Test (org.junit.Test)29 AuthenticationClient (co.cask.cdap.security.authentication.client.AuthenticationClient)16 URL (java.net.URL)15 HttpRequest (co.cask.common.http.HttpRequest)13 HttpFailureException (co.cask.common.http.exception.HttpFailureException)10 HttpResponse (co.cask.common.http.HttpResponse)6 ConnectionConfig (co.cask.cdap.client.config.ConnectionConfig)2 IOException (java.io.IOException)2 Properties (java.util.Properties)2 ExecutionException (java.util.concurrent.ExecutionException)2 DatasetProperties (co.cask.cdap.api.dataset.DatasetProperties)1 StreamEvent (co.cask.cdap.api.flow.flowlet.StreamEvent)1 ClientConfig (co.cask.cdap.client.config.ClientConfig)1 BadRequestException (co.cask.cdap.common.BadRequestException)1 StreamNotFoundException (co.cask.cdap.common.StreamNotFoundException)1 UnauthenticatedException (co.cask.cdap.common.UnauthenticatedException)1 ExploreDriver (co.cask.cdap.explore.jdbc.ExploreDriver)1 Credential (co.cask.cdap.security.authentication.client.Credential)1 BasicAuthenticationClient (co.cask.cdap.security.authentication.client.basic.BasicAuthenticationClient)1