Search in sources :

Example 1 with HttpResponseWrapper

use of org.opencastproject.security.util.HttpResponseWrapper in project opencast by opencast.

the class TrustedHttpClientImpl method retryAuthAndRequestAfterNonceTimeout.

/**
 * Retries a request if the nonce timed out during the request.
 *
 * @param httpUriRequest
 *         The request to be made that isn't a GET, those are handled automatically.
 * @param response
 *         The response with the bad nonce timeout in it.
 * @return A new response for the request if it was successful without the nonce timing out again or just the same
 * response it got if it ran out of attempts.
 * @throws TrustedHttpClientException
 * @throws IOException
 * @throws ClientProtocolException
 */
private HttpResponse retryAuthAndRequestAfterNonceTimeout(HttpUriRequest httpUriRequest, HttpResponse response) throws TrustedHttpClientException, IOException, ClientProtocolException {
    // Get rid of old security headers with the old nonce.
    httpUriRequest.removeHeaders(AUTHORIZATION_HEADER_NAME);
    for (int i = 0; i < nonceTimeoutRetries; i++) {
        HttpClient httpClient = makeHttpClient(DEFAULT_CONNECTION_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
        int variableDelay = 0;
        // Make sure that we have a variable delay greater than 0.
        if (retryMaximumVariableTime > 0) {
            variableDelay = generator.nextInt(retryMaximumVariableTime * MILLISECONDS_IN_SECONDS);
        }
        long totalDelay = (retryBaseDelay * MILLISECONDS_IN_SECONDS + variableDelay);
        if (totalDelay > 0) {
            logger.info("Sleeping " + totalDelay + "ms before trying request " + httpUriRequest.getURI() + " again due to a " + response.getStatusLine());
            try {
                Thread.sleep(totalDelay);
            } catch (InterruptedException e) {
                logger.error("Suffered InteruptedException while trying to sleep until next retry.", e);
            }
        }
        manuallyHandleDigestAuthentication(httpUriRequest, httpClient);
        response = new HttpResponseWrapper(httpClient.execute(httpUriRequest));
        if (!hadNonceTimeoutResponse(response)) {
            responseMap.put(response, httpClient);
            break;
        }
        httpClient.getConnectionManager().shutdown();
    }
    return response;
}
Also used : HttpResponseWrapper(org.opencastproject.security.util.HttpResponseWrapper) TrustedHttpClient(org.opencastproject.security.api.TrustedHttpClient) HttpClient(org.opencastproject.kernel.http.api.HttpClient)

Example 2 with HttpResponseWrapper

use of org.opencastproject.security.util.HttpResponseWrapper in project opencast by opencast.

the class TrustedHttpClientImpl method execute.

@Override
public HttpResponse execute(HttpUriRequest httpUriRequest, int connectionTimeout, int socketTimeout) throws TrustedHttpClientException {
    final HttpClient httpClient = makeHttpClient(connectionTimeout, socketTimeout);
    // Add the request header to elicit a digest auth response
    httpUriRequest.setHeader(REQUESTED_AUTH_HEADER, DIGEST_AUTH);
    httpUriRequest.setHeader(SecurityConstants.AUTHORIZATION_HEADER, "true");
    if (serviceRegistry != null && serviceRegistry.getCurrentJob() != null) {
        httpUriRequest.setHeader(CURRENT_JOB_HEADER, Long.toString(serviceRegistry.getCurrentJob().getId()));
    }
    // If a security service has been set, use it to pass the current security context on
    logger.debug("Adding security context to request");
    final Organization organization = securityService.getOrganization();
    if (organization != null) {
        httpUriRequest.setHeader(SecurityConstants.ORGANIZATION_HEADER, organization.getId());
        final User currentUser = securityService.getUser();
        if (currentUser != null) {
            httpUriRequest.setHeader(SecurityConstants.USER_HEADER, currentUser.getUsername());
        }
    }
    if ("GET".equalsIgnoreCase(httpUriRequest.getMethod()) || "HEAD".equalsIgnoreCase(httpUriRequest.getMethod())) {
        // Set the user/pass
        final UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass);
        httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
        // Run the request (the http client handles the multiple back-and-forth requests)
        try {
            Opt<HttpUriRequest> optSignedHttpUriRequest = getSignedUrl(httpUriRequest);
            HttpResponse response;
            if (optSignedHttpUriRequest.isSome()) {
                logger.debug("Adding url signing to request {} so that it is {}", httpUriRequest.getURI().toString(), optSignedHttpUriRequest.get().getURI().toString());
                response = new HttpResponseWrapper(httpClient.execute(optSignedHttpUriRequest.get()));
            } else {
                logger.debug("Not adding url signing to request {}", httpUriRequest.getURI().toString());
                response = new HttpResponseWrapper(httpClient.execute(httpUriRequest));
            }
            responseMap.put(response, httpClient);
            return response;
        } catch (IOException e) {
            // close the http connection(s)
            httpClient.getConnectionManager().shutdown();
            throw new TrustedHttpClientException(e);
        }
    } else {
        // HttpClient doesn't handle the request dynamics for other verbs (especially when sending a streamed multipart
        // request), so we need to handle the details of the digest auth back-and-forth manually
        manuallyHandleDigestAuthentication(httpUriRequest, httpClient);
        HttpResponse response = null;
        try {
            response = new HttpResponseWrapper(httpClient.execute(httpUriRequest));
            if (nonceTimeoutRetries > 0 && hadNonceTimeoutResponse(response)) {
                httpClient.getConnectionManager().shutdown();
                response = retryAuthAndRequestAfterNonceTimeout(httpUriRequest, response);
            }
            responseMap.put(response, httpClient);
            return response;
        } catch (Exception e) {
            // if we have a response, remove it from the map
            if (response != null) {
                responseMap.remove(response);
            }
            // close the http connection(s)
            httpClient.getConnectionManager().shutdown();
            throw new TrustedHttpClientException(e);
        }
    }
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpResponseWrapper(org.opencastproject.security.util.HttpResponseWrapper) Organization(org.opencastproject.security.api.Organization) User(org.opencastproject.security.api.User) TrustedHttpClient(org.opencastproject.security.api.TrustedHttpClient) HttpClient(org.opencastproject.kernel.http.api.HttpClient) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) TrustedHttpClientException(org.opencastproject.security.api.TrustedHttpClientException) ClientProtocolException(org.apache.http.client.ClientProtocolException) UrlSigningException(org.opencastproject.security.urlsigning.exception.UrlSigningException) IOException(java.io.IOException) TrustedHttpClientException(org.opencastproject.security.api.TrustedHttpClientException) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 3 with HttpResponseWrapper

use of org.opencastproject.security.util.HttpResponseWrapper in project opencast by opencast.

the class TrustedHttpClientImpl method getRealmAndNonce.

/**
 * Perform a request, and extract the realm and nonce values
 *
 * @param request
 *         The request to execute in order to obtain the realm and nonce
 * @return A String[] containing the {realm, nonce}
 */
protected String[] getRealmAndNonce(HttpRequestBase request) throws TrustedHttpClientException {
    HttpClient httpClient = makeHttpClient(DEFAULT_CONNECTION_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
    HttpResponse response;
    try {
        response = new HttpResponseWrapper(httpClient.execute(request));
    } catch (IOException e) {
        httpClient.getConnectionManager().shutdown();
        throw new TrustedHttpClientException(e);
    }
    Header[] headers = response.getHeaders("WWW-Authenticate");
    if (headers == null || headers.length == 0) {
        logger.warn("URI {} does not support digest authentication", request.getURI());
        httpClient.getConnectionManager().shutdown();
        return null;
    }
    Header authRequiredResponseHeader = headers[0];
    String nonce = null;
    String realm = null;
    for (HeaderElement element : authRequiredResponseHeader.getElements()) {
        if ("nonce".equals(element.getName())) {
            nonce = element.getValue();
        } else if ("Digest realm".equals(element.getName())) {
            realm = element.getValue();
        }
    }
    httpClient.getConnectionManager().shutdown();
    return new String[] { realm, nonce };
}
Also used : HttpResponseWrapper(org.opencastproject.security.util.HttpResponseWrapper) Header(org.apache.http.Header) HeaderElement(org.apache.http.HeaderElement) TrustedHttpClient(org.opencastproject.security.api.TrustedHttpClient) HttpClient(org.opencastproject.kernel.http.api.HttpClient) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) TrustedHttpClientException(org.opencastproject.security.api.TrustedHttpClientException)

Aggregations

HttpClient (org.opencastproject.kernel.http.api.HttpClient)3 TrustedHttpClient (org.opencastproject.security.api.TrustedHttpClient)3 HttpResponseWrapper (org.opencastproject.security.util.HttpResponseWrapper)3 IOException (java.io.IOException)2 HttpResponse (org.apache.http.HttpResponse)2 TrustedHttpClientException (org.opencastproject.security.api.TrustedHttpClientException)2 Header (org.apache.http.Header)1 HeaderElement (org.apache.http.HeaderElement)1 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)1 ClientProtocolException (org.apache.http.client.ClientProtocolException)1 HttpUriRequest (org.apache.http.client.methods.HttpUriRequest)1 Organization (org.opencastproject.security.api.Organization)1 User (org.opencastproject.security.api.User)1 UrlSigningException (org.opencastproject.security.urlsigning.exception.UrlSigningException)1