List of usage examples for org.apache.http.impl.auth BasicSchemeFactory BasicSchemeFactory
public BasicSchemeFactory(final Charset charset)
From source file:org.openscore.content.httpclient.build.auth.AuthSchemeProviderLookupBuilder.java
public Lookup<AuthSchemeProvider> buildAuthSchemeProviderLookup() { RegistryBuilder<AuthSchemeProvider> registryBuilder = RegistryBuilder.create(); for (String type : authTypes) { switch (type.trim()) { case "NTLM": registryBuilder.register(AuthSchemes.NTLM, new AuthSchemeProvider() { @Override// w w w . j a va 2 s. c o m public AuthScheme create(HttpContext httpContext) { return new NTLMScheme(new JCIFSEngine()); } }); break; case "BASIC": registryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory(Charset.forName("UTF-8"))); String value = username + ":" + password; byte[] encodedValue = Base64.encodeBase64(value.getBytes(StandardCharsets.UTF_8)); headers.add(new BasicHeader("Authorization", "Basic " + new String(encodedValue))); break; case "DIGEST": registryBuilder.register(AuthSchemes.DIGEST, new DigestSchemeFactory()); break; case "KERBEROS": if (getSettingsKey().equals(System.getProperty("oohttpclient.krb.last.settings"))) { break; } if (kerberosConfigFile != null) { System.setProperty("java.security.krb5.conf", kerberosConfigFile); } else { File krb5Config; String domain = host.replaceAll(".*\\.(?=.*\\.)", ""); try { krb5Config = createKrb5Configuration(domain); } catch (IOException e) { throw new RuntimeException("could not create the krb5 config file" + e.getMessage(), e); } System.setProperty("java.security.krb5.conf", krb5Config.toURI().toString()); } if (kerberosLoginConfigFile != null) { System.setProperty("java.security.auth.login.config", kerberosLoginConfigFile); } else { File loginConfig; try { loginConfig = createLoginConfig(); } catch (IOException e) { throw new RuntimeException( "could not create the kerberos login config file" + e.getMessage(), e); } System.setProperty("java.security.auth.login.config", loginConfig.toURI().toString()); } //todo fix security issue if (password != null) { System.setProperty(KrbHttpLoginModule.PAS, password); } if (username != null) { System.setProperty(KrbHttpLoginModule.USR, username); } System.setProperty("javax.security.auth.useSubjectCredsOnly", "false"); boolean skipPort = Boolean.parseBoolean(skipPortAtKerberosDatabaseLookup); registryBuilder.register(AuthSchemes.KERBEROS, new KerberosSchemeFactory(skipPort)); registryBuilder.register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(skipPort)); System.setProperty("oohttpclient.krb.last.settings", getSettingsKey()); break; default: throw new IllegalStateException( "Unsupported '" + HttpClientInputs.AUTH_TYPE + "'authentication scheme: " + type); } } return registryBuilder.build(); }
From source file:io.cloudslang.content.httpclient.build.auth.AuthSchemeProviderLookupBuilder.java
public Lookup<AuthSchemeProvider> buildAuthSchemeProviderLookup() { RegistryBuilder<AuthSchemeProvider> registryBuilder = RegistryBuilder.create(); for (String type : authTypes) { switch (type.trim()) { case "NTLM": registryBuilder.register(AuthSchemes.NTLM, new AuthSchemeProvider() { @Override/*from w w w .j a v a 2 s . co m*/ public AuthScheme create(HttpContext httpContext) { return new NTLMScheme(new JCIFSEngine()); } }); break; case "BASIC": registryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory(Charset.forName(Utils.DEFAULT_CHARACTER_SET))); String value = username + ":" + password; byte[] encodedValue = Base64.encodeBase64(value.getBytes(StandardCharsets.UTF_8)); headers.add(new BasicHeader("Authorization", "Basic " + new String(encodedValue))); break; case "DIGEST": registryBuilder.register(AuthSchemes.DIGEST, new DigestSchemeFactory()); break; case "KERBEROS": if (kerberosConfigFile != null) { System.setProperty("java.security.krb5.conf", kerberosConfigFile); } else { File krb5Config; String domain = host.replaceAll(".*\\.(?=.*\\.)", ""); try { krb5Config = createKrb5Configuration(domain); } catch (IOException e) { throw new RuntimeException("could not create the krb5 config file" + e.getMessage(), e); } System.setProperty("java.security.krb5.conf", krb5Config.toURI().toString()); } if (kerberosLoginConfigFile != null) { System.setProperty("java.security.auth.login.config", kerberosLoginConfigFile); } else { File loginConfig; try { loginConfig = createLoginConfig(); } catch (IOException e) { throw new RuntimeException( "could not create the kerberos login config file" + e.getMessage(), e); } System.setProperty("java.security.auth.login.config", loginConfig.toURI().toString()); } if (password != null) { System.setProperty(KrbHttpLoginModule.PAS, password); } if (username != null) { System.setProperty(KrbHttpLoginModule.USR, username); } System.setProperty("javax.security.auth.useSubjectCredsOnly", "false"); boolean skipPort = Boolean.parseBoolean(skipPortAtKerberosDatabaseLookup); registryBuilder.register(AuthSchemes.KERBEROS, new KerberosSchemeFactory(skipPort)); registryBuilder.register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(skipPort)); break; case AuthTypes.ANONYMOUS: break; default: throw new IllegalStateException( "Unsupported '" + HttpClientInputs.AUTH_TYPE + "'authentication scheme: " + type); } } return registryBuilder.build(); }
From source file:ch.cyberduck.core.http.HttpConnectionPoolBuilder.java
public HttpClientBuilder build(final TranscriptListener listener) { // Use HTTP Connect proxy implementation provided here instead of // relying on internal proxy support in socket factory final Proxy proxy = proxyFinder.find(host); if (proxy.getType() == Proxy.Type.HTTP) { final HttpHost h = new HttpHost(proxy.getHostname(), proxy.getPort(), Scheme.http.name()); if (log.isInfoEnabled()) { log.info(String.format("Setup proxy %s", h)); }/* www. j a v a 2 s . c om*/ builder.setProxy(h); } if (proxy.getType() == Proxy.Type.HTTPS) { final HttpHost h = new HttpHost(proxy.getHostname(), proxy.getPort(), Scheme.https.name()); if (log.isInfoEnabled()) { log.info(String.format("Setup proxy %s", h)); } builder.setProxy(h); } builder.setUserAgent(new PreferencesUseragentProvider().get()); final int timeout = preferences.getInteger("connection.timeout.seconds") * 1000; builder.setDefaultSocketConfig(SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(timeout).build()); builder.setDefaultRequestConfig(RequestConfig.custom().setRedirectsEnabled(true) // Disable use of Expect: Continue by default for all methods .setExpectContinueEnabled(false).setAuthenticationEnabled(true).setConnectTimeout(timeout) // Sets the timeout in milliseconds used when retrieving a connection from the ClientConnectionManager .setConnectionRequestTimeout(preferences.getInteger("http.manager.timeout")) .setSocketTimeout(timeout).build()); final String encoding; if (null == host.getEncoding()) { encoding = preferences.getProperty("browser.charset.encoding"); } else { encoding = host.getEncoding(); } builder.setDefaultConnectionConfig( ConnectionConfig.custom().setBufferSize(preferences.getInteger("http.socket.buffer")) .setCharset(Charset.forName(encoding)).build()); if (preferences.getBoolean("http.connections.reuse")) { builder.setConnectionReuseStrategy(new DefaultConnectionReuseStrategy()); } else { builder.setConnectionReuseStrategy(new NoConnectionReuseStrategy()); } builder.setRetryHandler( new ExtendedHttpRequestRetryHandler(preferences.getInteger("http.connections.retry"))); if (!preferences.getBoolean("http.compression.enable")) { builder.disableContentCompression(); } builder.setRequestExecutor(new LoggingHttpRequestExecutor(listener)); // Always register HTTP for possible use with proxy. Contains a number of protocol properties such as the // default port and the socket factory to be used to create the java.net.Socket instances for the given protocol builder.setConnectionManager(this.pool(this.registry().build())); builder.setDefaultAuthSchemeRegistry(RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.BASIC, new BasicSchemeFactory( Charset.forName(preferences.getProperty("http.credentials.charset")))) .register(AuthSchemes.DIGEST, new DigestSchemeFactory( Charset.forName(preferences.getProperty("http.credentials.charset")))) .register(AuthSchemes.NTLM, new NTLMSchemeFactory()) .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory()) .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).build()); return builder; }
From source file:com.mirth.connect.connectors.http.HttpDispatcher.java
@Override public Response send(ConnectorProperties connectorProperties, ConnectorMessage connectorMessage) { HttpDispatcherProperties httpDispatcherProperties = (HttpDispatcherProperties) connectorProperties; eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(), getDestinationName(), ConnectionStatusEventType.WRITING)); String responseData = null;/*from w ww.j a va 2 s .c o m*/ String responseError = null; String responseStatusMessage = null; Status responseStatus = Status.QUEUED; boolean validateResponse = false; CloseableHttpClient client = null; HttpRequestBase httpMethod = null; CloseableHttpResponse httpResponse = null; File tempFile = null; int socketTimeout = NumberUtils.toInt(httpDispatcherProperties.getSocketTimeout(), 30000); try { configuration.configureDispatcher(this, httpDispatcherProperties); long dispatcherId = getDispatcherId(); client = clients.get(dispatcherId); if (client == null) { BasicHttpClientConnectionManager httpClientConnectionManager = new BasicHttpClientConnectionManager( socketFactoryRegistry.build()); httpClientConnectionManager .setSocketConfig(SocketConfig.custom().setSoTimeout(socketTimeout).build()); HttpClientBuilder clientBuilder = HttpClients.custom() .setConnectionManager(httpClientConnectionManager); HttpUtil.configureClientBuilder(clientBuilder); if (httpDispatcherProperties.isUseProxyServer()) { clientBuilder.setRoutePlanner(new DynamicProxyRoutePlanner()); } client = clientBuilder.build(); clients.put(dispatcherId, client); } URI hostURI = new URI(httpDispatcherProperties.getHost()); String host = hostURI.getHost(); String scheme = hostURI.getScheme(); int port = hostURI.getPort(); if (port == -1) { if (scheme.equalsIgnoreCase("https")) { port = 443; } else { port = 80; } } // Parse the content type field first, and then add the charset if needed ContentType contentType = ContentType.parse(httpDispatcherProperties.getContentType()); Charset charset = null; if (contentType.getCharset() == null) { charset = Charset.forName(CharsetUtils.getEncoding(httpDispatcherProperties.getCharset())); } else { charset = contentType.getCharset(); } if (httpDispatcherProperties.isMultipart()) { tempFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp"); } HttpHost target = new HttpHost(host, port, scheme); httpMethod = buildHttpRequest(hostURI, httpDispatcherProperties, connectorMessage, tempFile, contentType, charset); HttpClientContext context = HttpClientContext.create(); // authentication if (httpDispatcherProperties.isUseAuthentication()) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM); Credentials credentials = new UsernamePasswordCredentials(httpDispatcherProperties.getUsername(), httpDispatcherProperties.getPassword()); credsProvider.setCredentials(authScope, credentials); AuthCache authCache = new BasicAuthCache(); RegistryBuilder<AuthSchemeProvider> registryBuilder = RegistryBuilder.<AuthSchemeProvider>create(); if (AuthSchemes.DIGEST.equalsIgnoreCase(httpDispatcherProperties.getAuthenticationType())) { logger.debug("using Digest authentication"); registryBuilder.register(AuthSchemes.DIGEST, new DigestSchemeFactory(charset)); if (httpDispatcherProperties.isUsePreemptiveAuthentication()) { processDigestChallenge(authCache, target, credentials, httpMethod, context); } } else { logger.debug("using Basic authentication"); registryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory(charset)); if (httpDispatcherProperties.isUsePreemptiveAuthentication()) { authCache.put(target, new BasicScheme()); } } context.setCredentialsProvider(credsProvider); context.setAuthSchemeRegistry(registryBuilder.build()); context.setAuthCache(authCache); logger.debug("using authentication with credentials: " + credentials); } RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(socketTimeout) .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true).build(); context.setRequestConfig(requestConfig); // Set proxy information if (httpDispatcherProperties.isUseProxyServer()) { context.setAttribute(PROXY_CONTEXT_KEY, new HttpHost(httpDispatcherProperties.getProxyAddress(), Integer.parseInt(httpDispatcherProperties.getProxyPort()))); } // execute the method logger.debug( "executing method: type=" + httpMethod.getMethod() + ", uri=" + httpMethod.getURI().toString()); httpResponse = client.execute(target, httpMethod, context); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); logger.debug("received status code: " + statusCode); Map<String, List<String>> headers = new HashMap<String, List<String>>(); for (Header header : httpResponse.getAllHeaders()) { List<String> list = headers.get(header.getName()); if (list == null) { list = new ArrayList<String>(); headers.put(header.getName(), list); } list.add(header.getValue()); } connectorMessage.getConnectorMap().put("responseStatusLine", statusLine.toString()); connectorMessage.getConnectorMap().put("responseHeaders", new MessageHeaders(new CaseInsensitiveMap(headers))); ContentType responseContentType = ContentType.get(httpResponse.getEntity()); if (responseContentType == null) { responseContentType = ContentType.TEXT_PLAIN; } Charset responseCharset = charset; if (responseContentType.getCharset() != null) { responseCharset = responseContentType.getCharset(); } final String responseBinaryMimeTypes = httpDispatcherProperties.getResponseBinaryMimeTypes(); BinaryContentTypeResolver binaryContentTypeResolver = new BinaryContentTypeResolver() { @Override public boolean isBinaryContentType(ContentType contentType) { return HttpDispatcher.this.isBinaryContentType(responseBinaryMimeTypes, contentType); } }; /* * First parse out the body of the HTTP response. Depending on the connector settings, * this could end up being a string encoded with the response charset, a byte array * representing the raw response payload, or a MimeMultipart object. */ Object responseBody = ""; // The entity could be null in certain cases such as 204 responses if (httpResponse.getEntity() != null) { // Only parse multipart if XML Body is selected and Parse Multipart is enabled if (httpDispatcherProperties.isResponseXmlBody() && httpDispatcherProperties.isResponseParseMultipart() && responseContentType.getMimeType().startsWith(FileUploadBase.MULTIPART)) { responseBody = new MimeMultipart(new ByteArrayDataSource(httpResponse.getEntity().getContent(), responseContentType.toString())); } else if (binaryContentTypeResolver.isBinaryContentType(responseContentType)) { responseBody = IOUtils.toByteArray(httpResponse.getEntity().getContent()); } else { responseBody = IOUtils.toString(httpResponse.getEntity().getContent(), responseCharset); } } /* * Now that we have the response body, we need to create the actual Response message * data. Depending on the connector settings this could be our custom serialized XML, a * Base64 string encoded from the raw response payload, or a string encoded from the * payload with the request charset. */ if (httpDispatcherProperties.isResponseXmlBody()) { responseData = HttpMessageConverter.httpResponseToXml(statusLine.toString(), headers, responseBody, responseContentType, httpDispatcherProperties.isResponseParseMultipart(), httpDispatcherProperties.isResponseIncludeMetadata(), binaryContentTypeResolver); } else if (responseBody instanceof byte[]) { responseData = new String(Base64Util.encodeBase64((byte[]) responseBody), "US-ASCII"); } else { responseData = (String) responseBody; } validateResponse = httpDispatcherProperties.getDestinationConnectorProperties().isValidateResponse(); if (statusCode < HttpStatus.SC_BAD_REQUEST) { responseStatus = Status.SENT; } else { eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(), connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(), connectorProperties.getName(), "Received error response from HTTP server.", null)); responseStatusMessage = ErrorMessageBuilder .buildErrorResponse("Received error response from HTTP server.", null); responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(), responseData, null); } } catch (Exception e) { eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(), connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(), connectorProperties.getName(), "Error connecting to HTTP server.", e)); responseStatusMessage = ErrorMessageBuilder.buildErrorResponse("Error connecting to HTTP server", e); responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(), "Error connecting to HTTP server", e); } finally { try { HttpClientUtils.closeQuietly(httpResponse); // Delete temp files if we created them if (tempFile != null) { tempFile.delete(); tempFile = null; } } finally { eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(), getDestinationName(), ConnectionStatusEventType.IDLE)); } } return new Response(responseStatus, responseData, responseStatusMessage, responseError, validateResponse); }
From source file:org.jboss.as.test.integration.security.common.Utils.java
/** * Returns response body for the given URL request as a String. It also checks if the returned HTTP status code is the * expected one. If the server returns {@link HttpServletResponse#SC_UNAUTHORIZED} and username is provided, then a new * request is created with the provided credentials (basic authentication). * * @param url URL to which the request should be made * @param user Username (may be null)/*from ww w . j a v a2s .c o m*/ * @param pass Password (may be null) * @param expectedStatusCode expected status code returned from the requested server * @param checkFollowupAuthState whether to check auth state for followup request - if set to true, followup * request is sent to server and 200 OK is expected directly (no re-authentication * challenge - 401 Unauthorized - is expected) * @return HTTP response body * @throws IOException * @throws URISyntaxException */ public static String makeCallWithBasicAuthn(URL url, String user, String pass, int expectedStatusCode, boolean checkFollowupAuthState) throws IOException, URISyntaxException { LOGGER.trace("Requesting URL " + url); // use UTF-8 charset for credentials Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.BASIC, new BasicSchemeFactory(Consts.UTF_8)) .register(AuthSchemes.DIGEST, new DigestSchemeFactory(Consts.UTF_8)).build(); try (final CloseableHttpClient httpClient = HttpClientBuilder.create() .setDefaultAuthSchemeRegistry(authSchemeRegistry).build()) { final HttpGet httpGet = new HttpGet(url.toURI()); HttpResponse response = httpClient.execute(httpGet); int statusCode = response.getStatusLine().getStatusCode(); if (HttpServletResponse.SC_UNAUTHORIZED != statusCode || StringUtils.isEmpty(user)) { assertEquals("Unexpected HTTP response status code.", expectedStatusCode, statusCode); return EntityUtils.toString(response.getEntity()); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("HTTP response was SC_UNAUTHORIZED, let's authenticate the user " + user); } HttpEntity entity = response.getEntity(); if (entity != null) EntityUtils.consume(entity); final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, pass); HttpClientContext hc = new HttpClientContext(); hc.setCredentialsProvider(new BasicCredentialsProvider()); hc.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()), credentials); //enable auth response = httpClient.execute(httpGet, hc); statusCode = response.getStatusLine().getStatusCode(); assertEquals("Unexpected status code returned after the authentication.", expectedStatusCode, statusCode); if (checkFollowupAuthState) { // Let's disable authentication for this client as we already have all the context neccessary to be // authorized (we expect that gained 'nonce' value can be re-used in our case here). // By disabling authentication we simply get first server response and thus we can check whether we've // got 200 OK or different response code. RequestConfig reqConf = RequestConfig.custom().setAuthenticationEnabled(false).build(); httpGet.setConfig(reqConf); response = httpClient.execute(httpGet, hc); statusCode = response.getStatusLine().getStatusCode(); assertEquals("Unexpected status code returned after the authentication.", HttpURLConnection.HTTP_OK, statusCode); } return EntityUtils.toString(response.getEntity()); } }