use of org.apache.http.impl.auth.BasicScheme in project fess by codelibs.
the class DataConfig method getAuthScheme.
private AuthScheme getAuthScheme(final Map<String, String> paramMap, final String webAuthName, final String scheme) {
AuthScheme authScheme = null;
if (Constants.BASIC.equals(scheme)) {
authScheme = new BasicScheme();
} else if (Constants.DIGEST.equals(scheme)) {
authScheme = new DigestScheme();
} else if (Constants.NTLM.equals(scheme)) {
final Properties props = new Properties();
paramMap.entrySet().stream().filter(e -> e.getKey().startsWith("jcifs.")).forEach(e -> {
props.setProperty(e.getKey(), e.getValue());
});
authScheme = new NTLMScheme(new JcifsEngine(props));
} else if (Constants.FORM.equals(scheme)) {
final String prefix = CRAWLER_WEB_AUTH + "." + webAuthName + ".";
final Map<String, String> parameterMap = paramMap.entrySet().stream().filter(e -> e.getKey().startsWith(prefix)).collect(Collectors.toMap(e -> e.getKey().substring(prefix.length()), Entry::getValue));
authScheme = new FormScheme(parameterMap);
}
return authScheme;
}
use of org.apache.http.impl.auth.BasicScheme in project ontrack by nemerosa.
the class OTHttpClientBuilder method build.
public OTHttpClient build() {
HttpClientContext httpContext = HttpClientContext.create();
// Basic authentication
if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(host), new UsernamePasswordCredentials(username, password));
AuthCache authCache = new BasicAuthCache();
authCache.put(host, new BasicScheme());
httpContext.setCredentialsProvider(credentialsProvider);
httpContext.setAuthCache(authCache);
}
CookieStore cookieStore = new BasicCookieStore();
httpContext.setCookieStore(cookieStore);
// SSL setup
SSLConnectionSocketFactory sslSocketFactory;
if (disableSsl) {
logger.warn("Disabling SSL checks!");
SSLContext ctx;
try {
X509TrustManager x509TrustManager = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx = SSLContext.getInstance("TLS");
ctx.init(new KeyManager[0], new TrustManager[] { x509TrustManager }, new SecureRandom());
} catch (NoSuchAlgorithmException | KeyManagementException e) {
throw new OTHttpClientSSLSetupException(e);
}
sslSocketFactory = new SSLConnectionSocketFactory(ctx, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
} else {
sslSocketFactory = SSLConnectionSocketFactory.getSocketFactory();
}
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslSocketFactory).build();
Supplier<CloseableHttpClient> httpClientSupplier = () -> {
// Defaults
HttpClientBuilder builder = HttpClientBuilder.create().setConnectionManager(new PoolingHttpClientConnectionManager(registry));
// OK
return builder.build();
};
return new OTHttpClientImpl(url, host, httpClientSupplier, httpContext, clientLogger);
}
use of org.apache.http.impl.auth.BasicScheme in project SmartAndroidSource by jaychou2012.
the class PreemtiveAuthorizationHttpRequestInterceptor method process.
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
if (authState.getAuthScheme() == null) {
AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
Credentials creds = credsProvider.getCredentials(authScope);
if (creds != null) {
authState.setAuthScheme(new BasicScheme());
authState.setCredentials(creds);
}
}
}
use of org.apache.http.impl.auth.BasicScheme 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.auth.BasicScheme 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;
}
Aggregations