use of org.apache.http.impl.client.BasicAuthCache in project iaf by ibissource.
the class HttpSenderBase method setupAuthentication.
private void setupAuthentication(CredentialFactory user_cf, CredentialFactory proxyCredentials, HttpHost proxy, Builder requestConfigBuilder) {
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
if (StringUtils.isNotEmpty(user_cf.getUsername()) || StringUtils.isNotEmpty(getTokenEndpoint())) {
credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), getCredentials());
AuthenticationScheme preferredAuthenticationScheme = getPreferredAuthenticationScheme();
requestConfigBuilder.setTargetPreferredAuthSchemes(Arrays.asList(preferredAuthenticationScheme.getSchemeName()));
requestConfigBuilder.setAuthenticationEnabled(true);
if (preferredAuthenticationScheme == AuthenticationScheme.OAUTH) {
CredentialFactory client_cf = new CredentialFactory(getClientAuthAlias(), getClientId(), getClientSecret());
OAuthAccessTokenManager accessTokenManager = new OAuthAccessTokenManager(getTokenEndpoint(), getScope(), client_cf, StringUtils.isEmpty(user_cf.getUsername()), this, getTokenExpiry());
httpClientContext.setAttribute(OAuthAuthenticationScheme.ACCESSTOKEN_MANAGER_KEY, accessTokenManager);
httpClientBuilder.setTargetAuthenticationStrategy(new OAuthPreferringAuthenticationStrategy());
}
}
if (proxy != null) {
AuthScope scope = new AuthScope(proxy, proxyRealm, AuthScope.ANY_SCHEME);
if (StringUtils.isNotEmpty(proxyCredentials.getUsername())) {
Credentials credentials = new UsernamePasswordCredentials(proxyCredentials.getUsername(), proxyCredentials.getPassword());
credentialsProvider.setCredentials(scope, credentials);
}
if (prefillProxyAuthCache()) {
requestConfigBuilder.setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC));
AuthCache authCache = httpClientContext.getAuthCache();
if (authCache == null)
authCache = new BasicAuthCache();
authCache.put(proxy, new BasicScheme());
httpClientContext.setAuthCache(authCache);
}
}
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
use of org.apache.http.impl.client.BasicAuthCache in project zm-mailbox by Zimbra.
the class WebDavClient method setCredential.
public void setCredential(String user, String pass, String targetUrl) {
mUsername = user;
mPassword = pass;
Credentials cred = new UsernamePasswordCredentials(mUsername, mPassword);
CredentialsProvider provider = new BasicCredentialsProvider();
provider.setCredentials(AuthScope.ANY, cred);
HttpHost targetHost = new HttpHost(targetUrl);
AuthCache authCache = new BasicAuthCache();
authCache.put(targetHost, new BasicScheme());
// Add AuthCache to the execution context
context = HttpClientContext.create();
context.setCredentialsProvider(provider);
context.setAuthCache(authCache);
}
use of org.apache.http.impl.client.BasicAuthCache in project zm-mailbox by Zimbra.
the class FeedManager method retrieveRemoteData.
private static RemoteDataInfo retrieveRemoteData(String url, Folder.SyncData fsd) throws ServiceException, HttpException, IOException {
assert !Strings.isNullOrEmpty(url);
HttpClientBuilder clientBuilder = ZimbraHttpConnectionManager.getExternalHttpConnMgr().newHttpClient();
HttpProxyUtil.configureProxy(clientBuilder);
// cannot set connection timeout because it'll affect all HttpClients associated with the conn mgr.
// see comments in ZimbraHttpConnectionManager
// client.setConnectionTimeout(10000);
SocketConfig config = SocketConfig.custom().setSoTimeout(60000).build();
clientBuilder.setDefaultSocketConfig(config);
ConnectionConfig connConfig = ConnectionConfig.custom().setCharset(Charset.forName(MimeConstants.P_CHARSET_UTF8)).build();
clientBuilder.setDefaultConnectionConfig(connConfig);
HttpGet get = null;
BufferedInputStream content = null;
long lastModified = 0;
String expectedCharset = MimeConstants.P_CHARSET_UTF8;
int redirects = 0;
int statusCode = HttpServletResponse.SC_NOT_FOUND;
try {
do {
String lcurl = url.toLowerCase();
if (lcurl.startsWith("webcal:")) {
url = "http:" + url.substring(7);
} else if (lcurl.startsWith("feed:")) {
url = "http:" + url.substring(5);
} else if (!lcurl.startsWith("http:") && !lcurl.startsWith("https:")) {
throw ServiceException.INVALID_REQUEST("url must begin with http: or https:", null);
}
// Add AuthCache to the execution context
HttpClientContext context = HttpClientContext.create();
URIBuilder httpurl;
try {
httpurl = new URIBuilder(url);
} catch (URISyntaxException e1) {
throw ServiceException.INVALID_REQUEST("invalid url for feed: " + url, e1);
}
// validate target address (also handles followed `location` header addresses)
if (isBlockedFeedAddress(httpurl)) {
ZimbraLog.misc.info("Feed ip address blocked: %s. See localconfig for comma-separated ip list configuration: " + "zimbra_feed_manager_blacklist, zimbra_feed_manager_whitelist", url);
throw ServiceException.INVALID_REQUEST(String.format("Address for feed is blocked: %s. See mailbox logs for details.", url), null);
}
// username and password are encoded in the URL as http://user:pass@host/...
if (url.indexOf('@') != -1) {
if (httpurl.getUserInfo() != null) {
String user = httpurl.getUserInfo();
if (user.indexOf('%') != -1) {
try {
user = URLDecoder.decode(user, "UTF-8");
} catch (OutOfMemoryError e) {
Zimbra.halt("out of memory", e);
} catch (Throwable t) {
}
}
int index = user.indexOf(':');
String userName = user.substring(0, index);
String password = user.substring(index + 1);
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userName, password);
provider.setCredentials(AuthScope.ANY, credentials);
clientBuilder.setDefaultCredentialsProvider(provider);
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
// Generate BASIC scheme object and add it to the local auth cache
BasicScheme basicAuth = new BasicScheme();
authCache.put(new HttpHost(httpurl.getHost()), basicAuth);
// Add AuthCache to the execution context
context.setCredentialsProvider(provider);
context.setAuthCache(authCache);
}
}
try {
get = new HttpGet(url);
} catch (OutOfMemoryError e) {
Zimbra.halt("out of memory", e);
return null;
} catch (Throwable t) {
ZimbraLog.misc.warnQuietly(String.format("invalid url for feed: %s", url), t);
throw ServiceException.INVALID_REQUEST("invalid url for feed: " + url, null);
}
DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
clientBuilder.setRedirectStrategy(redirectStrategy);
get.addHeader("User-Agent", HTTP_USER_AGENT);
get.addHeader("Accept", HTTP_ACCEPT);
if (fsd != null && fsd.getLastSyncDate() > 0) {
String lastSyncAt = DateUtils.formatDate(new Date(fsd.getLastSyncDate()));
get.addHeader("If-Modified-Since", lastSyncAt);
}
HttpClient client = clientBuilder.build();
HttpResponse response = HttpClientUtil.executeMethod(client, get, context);
Header locationHeader = response.getFirstHeader("location");
if (locationHeader != null) {
// update our target URL and loop again to do another HTTP GET
url = locationHeader.getValue();
get.releaseConnection();
} else {
statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpServletResponse.SC_OK) {
Header contentEncoding = response.getFirstHeader("Content-Encoding");
InputStream respInputStream = response.getEntity().getContent();
if (contentEncoding != null) {
if (contentEncoding.getValue().indexOf("gzip") != -1) {
respInputStream = new GZIPInputStream(respInputStream);
}
}
content = new BufferedInputStream(respInputStream);
org.apache.http.entity.ContentType contentType = org.apache.http.entity.ContentType.getOrDefault(response.getEntity());
if (contentType != null && contentType.getCharset() != null) {
expectedCharset = contentType.getCharset().name();
}
Header lastModHdr = response.getFirstHeader("Last-Modified");
if (lastModHdr == null) {
lastModHdr = response.getFirstHeader("Date");
}
if (lastModHdr != null) {
Date d = DateUtils.parseDate(lastModHdr.getValue());
lastModified = d.getTime();
} else {
lastModified = System.currentTimeMillis();
}
} else if (statusCode == HttpServletResponse.SC_NOT_MODIFIED) {
ZimbraLog.misc.debug("Remote data at " + url + " not modified since last sync");
return new RemoteDataInfo(statusCode, redirects, null, expectedCharset, lastModified);
} else {
throw ServiceException.RESOURCE_UNREACHABLE(response.getStatusLine().toString(), null);
}
break;
}
} while (++redirects <= MAX_REDIRECTS);
} catch (ServiceException ex) {
if (get != null) {
get.releaseConnection();
}
throw ex;
} catch (HttpException ex) {
if (get != null) {
get.releaseConnection();
}
throw ex;
} catch (IOException ex) {
if (get != null) {
get.releaseConnection();
}
throw ex;
}
RemoteDataInfo rdi = new RemoteDataInfo(statusCode, redirects, content, expectedCharset, lastModified);
rdi.setGetMethod(get);
return rdi;
}
use of org.apache.http.impl.client.BasicAuthCache in project qpid-broker-j by apache.
the class QpidRestAPIQueueCreator method getHttpClientContext.
private HttpClientContext getHttpClientContext(final HttpHost management) {
final BasicAuthCache authCache = new BasicAuthCache();
authCache.put(management, new BasicScheme());
HttpClientContext localContext = HttpClientContext.create();
localContext.setAuthCache(authCache);
return localContext;
}
use of org.apache.http.impl.client.BasicAuthCache in project ats-framework by Axway.
the class HttpClient method setupAuthentication.
/**
* Set up authentication for HTTP Basic/HTTP Digest/SPNEGO.
*
* @param httpClientBuilder The client builder
* @return The context
* @throws HttpException
*/
private void setupAuthentication(HttpClientBuilder httpClientBuilder) throws HttpException {
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(username, password));
httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
if (authType == AuthType.always) {
AuthCache authCache = new BasicAuthCache();
// Generate BASIC scheme object and add it to the local auth cache
BasicScheme basicAuth = new BasicScheme();
HttpHost target = new HttpHost(host, port, isOverSsl ? "https" : "http");
authCache.put(target, basicAuth);
// Add AuthCache to the execution context
httpContext.setAuthCache(authCache);
} else {
if (!StringUtils.isNullOrEmpty(kerberosServicePrincipalName)) {
GssClient gssClient = new GssClient(username, password, kerberosClientKeytab, krb5ConfFile);
AuthSchemeProvider nsf = new SPNegoSchemeFactory(gssClient, kerberosServicePrincipalName, kerberosServicePrincipalType);
final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO, nsf).build();
httpClientBuilder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
}
}
}
Aggregations