Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using AuthCache for Apache HttpClient to do pre-emptive authentication #85

Merged
merged 1 commit into from
Oct 13, 2015
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,17 @@ import com.twcable.grabbit.jcr.JcrUtil
import groovy.transform.CompileStatic
import groovy.util.logging.Slf4j
import org.apache.http.HttpEntity
import org.apache.http.HttpHost
import org.apache.http.HttpResponse
import org.apache.http.auth.AuthScope
import org.apache.http.auth.UsernamePasswordCredentials
import org.apache.http.client.AuthCache
import org.apache.http.client.CredentialsProvider
import org.apache.http.client.HttpClient
import org.apache.http.client.methods.HttpGet
import org.apache.http.client.protocol.HttpClientContext
import org.apache.http.impl.auth.BasicScheme
import org.apache.http.impl.client.BasicAuthCache
import org.apache.http.impl.client.BasicCredentialsProvider
import org.apache.http.impl.client.DefaultHttpClient
import org.apache.sling.jcr.api.SlingRepository
Expand Down Expand Up @@ -108,6 +114,24 @@ class ClientBatchJobExecutionListener implements JobExecutionListener {
client
}

/**
* Gets a new HttpClientContext for the given HttpRequest. The ClientContext sets up preemptive
* authentication using BasicAuthCache
* @param get the HttpGet request
* @return the HttpClientContext for given HttpRequest
*/
private HttpClientContext getHttpClientContext(HttpGet get) {
// Setup preemptive Authentication
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache()
HttpHost host = new HttpHost(get.URI.host, get.URI.port, get.URI.scheme)
authCache.put(host, new BasicScheme())
// Add AuthCache to the execution context
HttpClientContext context = HttpClientContext.create()
context.setAuthCache(authCache)
return context
}

/**
* Makes a Http Get request to the grab path and returns the response
* @param jobParameters that contain information like the path, host, port, etc.
Expand Down Expand Up @@ -135,7 +159,9 @@ class ClientBatchJobExecutionListener implements JobExecutionListener {

//create the get request
HttpGet get = new HttpGet(uriBuilder.build())
HttpResponse response = getHttpClient(username, password).execute(get)
HttpClient client = getHttpClient(username, password)
HttpClientContext context = getHttpClientContext(get)
HttpResponse response = client.execute(get, context)
response
}

Expand Down