public static void main(String... args) throws IOException { DefaultHttpClient httpclient = new DefaultHttpClient(); List<String> authpref = new ArrayList<String>(); authpref.add(AuthPolicy.NTLM); httpclient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref); NTCredentials creds = new NTCredentials("abhisheks", "abhiProJul17", "", ""); httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds); HttpHost target = new HttpHost("apps.prorigo.com", 80, "http"); // Make sure the same context is used to execute logically related requests HttpContext localContext = new BasicHttpContext(); // Execute a cheap method first. This will trigger NTLM authentication HttpGet httpget = new HttpGet("/conference/Booking"); HttpResponse response = httpclient.execute(target, httpget, localContext); HttpEntity entity = response.getEntity(); System.out.println(EntityUtils.toString(entity)); }
private static AbstractHttpClient createHTTPClient() { AbstractHttpClient client = new DefaultHttpClient(); String proxyHost = System.getProperty("https.proxyHost", ""); if (!proxyHost.isEmpty()) { int proxyPort = Integer.parseInt(System.getProperty("https.proxyPort", "-1")); log.info("Using proxy " + proxyHost + ":" + proxyPort); HttpParams params = client.getParams(); HttpHost proxy = new HttpHost(proxyHost, proxyPort); params.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); String proxyUser = System.getProperty(JMeter.HTTP_PROXY_USER, JMeterUtils.getProperty(JMeter.HTTP_PROXY_USER)); if (proxyUser != null) { log.info("Using authenticated proxy with username: " + proxyUser); String proxyPass = System.getProperty(JMeter.HTTP_PROXY_PASS, JMeterUtils.getProperty(JMeter.HTTP_PROXY_PASS)); String localHost; try { localHost = InetAddress.getLocalHost().getCanonicalHostName(); } catch (Throwable e) { log.error("Failed to get local host name, defaulting to 'localhost'", e); localHost = "localhost"; } AuthScope authscope = new AuthScope(proxyHost, proxyPort); String proxyDomain = JMeterUtils.getPropDefault("http.proxyDomain", ""); NTCredentials credentials = new NTCredentials(proxyUser, proxyPass, localHost, proxyDomain); client.getCredentialsProvider().setCredentials(authscope, credentials); } } return client; }
public static HttpCommandExecutor getProxyExecutor(URL url, Properties prop) { prop = decrypt(prop); String proxyHost = prop.getProperty("proxyHost"); int proxyPort = Integer.valueOf(prop.getProperty("proxyPort")); String proxyUserDomain = prop.getProperty("proxyUserDomain"); String proxyUser = prop.getProperty("proxyUser"); String proxyPassword = prop.getProperty("proxyPassword"); HttpClientBuilder builder = HttpClientBuilder.create(); HttpHost proxy = new HttpHost(proxyHost, proxyPort); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), new NTCredentials(proxyUser, proxyPassword, getWorkstation(), proxyUserDomain)); if (url.getUserInfo() != null && !url.getUserInfo().isEmpty()) { credsProvider.setCredentials(new AuthScope(url.getHost(), (url.getPort() > 0 ? url.getPort() : url.getDefaultPort())), new UsernamePasswordCredentials(proxyUser, proxyPassword)); } builder.setProxy(proxy); builder.setDefaultCredentialsProvider(credsProvider); HttpClient.Factory factory = new SimpleHttpClientFactory(builder); return new HttpCommandExecutor(new HashMap<String, CommandInfo>(), url, factory); }
public static HttpClient createNtlmProxyClient() { final String proxyHost = Configuration.getProperty("http.proxyHost"); final String proxyPort = Configuration.getProperty("http.proxyPort"); final String proxyUser = Configuration.getProperty("http.proxyUser"); final String proxyPassword = Configuration.getProperty("http.proxyPassword"); System.setProperty("http.proxyHost", proxyHost); System.setProperty("http.proxyPort", proxyPort); DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials( new AuthScope(proxyHost, Integer.parseInt(proxyPort)), new NTCredentials(proxyUser + ":" + proxyPassword)); HttpHost proxy = new HttpHost(proxyHost, Integer.parseInt(proxyPort)); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); return client; }
/** * Configure credentials and auth scheme on client if an authorization is * available for url * @param client {@link HttpClient} * @param url URL to test * @param credentialsProvider {@link CredentialsProvider} * @param localHost host running JMeter */ public void setupCredentials(HttpClient client, URL url, CredentialsProvider credentialsProvider, String localHost) { Authorization auth = getAuthForURL(url); if (auth != null) { String username = auth.getUser(); String realm = auth.getRealm(); String domain = auth.getDomain(); if (log.isDebugEnabled()){ log.debug(username + " > D="+domain+" R="+realm + " M="+auth.getMechanism()); } if (Mechanism.KERBEROS.equals(auth.getMechanism())) { ((AbstractHttpClient) client).getAuthSchemes().register( AuthSchemes.SPNEGO, new FixedSPNegoSchemeFactory(isStripPort(url))); credentialsProvider.setCredentials(new AuthScope(null, -1, null), USE_JAAS_CREDENTIALS); } else { credentialsProvider.setCredentials( new AuthScope(url.getHost(), url.getPort(), realm.length()==0 ? null : realm), new NTCredentials(username, auth.getPass(), localHost, domain)); } } }
@Test public void testNTLMAuthenticationFailure() throws Exception { this.serverBootstrap.registerHandler("*", new NtlmResponseHandler()); final HttpHost target = start(); final BasicCredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new NTCredentials("test", "test", null, null)); this.httpclient = HttpClients.custom() .setDefaultCredentialsProvider(credsProvider) .build(); final HttpContext context = HttpClientContext.create(); final HttpGet httpget = new HttpGet("/"); final HttpResponse response = this.httpclient.execute(target, httpget, context); EntityUtils.consume(response.getEntity()); Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode()); }
@Test public void testNTLMv1Type2Message() throws Exception { this.serverBootstrap.registerHandler("*", new NtlmType2MessageResponseHandler("TlRMTVNTUAACAA" + "AADAAMADgAAAAzggLiASNFZ4mrze8AAAAAAAAAAAAAAAAAAAAABgBwFwAAAA9T" + "AGUAcgB2AGUAcgA=")); final HttpHost target = start(); final BasicCredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new NTCredentials("test", "test", null, null)); this.httpclient = HttpClients.custom() .setDefaultCredentialsProvider(credsProvider) .build(); final HttpContext context = HttpClientContext.create(); final HttpGet httpget = new HttpGet("/"); final HttpResponse response = this.httpclient.execute(target, httpget, context); EntityUtils.consume(response.getEntity()); Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode()); }
@Test public void testNTLMv2Type2Message() throws Exception { this.serverBootstrap.registerHandler("*", new NtlmType2MessageResponseHandler("TlRMTVNTUAACAA" + "AADAAMADgAAAAzgoriASNFZ4mrze8AAAAAAAAAACQAJABEAAAABgBwFwAAAA9T" + "AGUAcgB2AGUAcgACAAwARABvAG0AYQBpAG4AAQAMAFMAZQByAHYAZQByAAAAAAA=")); final HttpHost target = start(); final BasicCredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new NTCredentials("test", "test", null, null)); this.httpclient = HttpClients.custom() .setDefaultCredentialsProvider(credsProvider) .build(); final HttpContext context = HttpClientContext.create(); final HttpGet httpget = new HttpGet("/"); final HttpResponse response = this.httpclient.execute(target, httpget, context); EntityUtils.consume(response.getEntity()); Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode()); }
@Test public void testNTLMType2MessageOnlyAuthenticationFailure() throws Exception { this.serverBootstrap.registerHandler("*", new NtlmType2MessageOnlyResponseHandler("TlRMTVNTUAACAA" + "AADAAMADgAAAAzggLiASNFZ4mrze8AAAAAAAAAAAAAAAAAAAAABgBwFwAAAA9T" + "AGUAcgB2AGUAcgA=")); final HttpHost target = start(); final HttpClientContext context = HttpClientContext.create(); final BasicCredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new NTCredentials("test", "test", null, null)); context.setCredentialsProvider(credsProvider); final HttpGet httpget = new HttpGet("/"); final HttpResponse response = this.httpclient.execute(target, httpget, context); EntityUtils.consume(response.getEntity()); Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode()); }
@Test public void testNTLMType2NonUnicodeMessageOnlyAuthenticationFailure() throws Exception { this.serverBootstrap.registerHandler("*", new NtlmType2MessageOnlyResponseHandler("TlRMTVNTUAACAA" + "AABgAGADgAAAAyggLiASNFZ4mrze8AAAAAAAAAAAAAAAAAAAAABgBwFwAAAA9T" + "ZXJ2ZXI=")); final HttpHost target = start(); final HttpClientContext context = HttpClientContext.create(); final BasicCredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new NTCredentials("test", "test", null, null)); context.setCredentialsProvider(credsProvider); final HttpGet httpget = new HttpGet("/"); final HttpResponse response = this.httpclient.execute(target, httpget, context); EntityUtils.consume(response.getEntity()); Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode()); }
@Test public void testProxyCredentials() throws Exception { HttpClient wdmClient = new HttpClient.Builder().proxy("myproxy:8081") .proxyUser("domain\\me").proxyPass("pass").build(); Field field = HttpClient.class.getDeclaredField("closeableHttpClient"); field.setAccessible(true); CloseableHttpClient client = (CloseableHttpClient) field.get(wdmClient); field = client.getClass().getDeclaredField("credentialsProvider"); field.setAccessible(true); BasicCredentialsProvider provider = (BasicCredentialsProvider) field .get(client); NTCredentials ntcreds = (NTCredentials) provider.getCredentials( new AuthScope(ANY_HOST, ANY_PORT, ANY_REALM, NTLM)); assertThat(ntcreds.getDomain(), equalTo("DOMAIN")); assertThat(ntcreds.getUserName(), equalTo("me")); assertThat(ntcreds.getPassword(), equalTo("pass")); UsernamePasswordCredentials creds = (UsernamePasswordCredentials) provider .getCredentials(new AuthScope(ANY_HOST, ANY_PORT)); assertThat(creds.getUserName(), equalTo("domain\\me")); assertThat(creds.getPassword(), equalTo("pass")); }
protected final CloseableHttpClient getHttpClient(final boolean useSpnego) throws Exception { final CredentialsProvider credsProvider = new BasicCredentialsProvider(); final HttpClientBuilder hcb = HttpClients.custom(); if (useSpnego) { //SPNEGO/Kerberos setup log.debug("SPNEGO activated"); final AuthSchemeProvider nsf = new SPNegoSchemeFactory(true);// new NegotiateSchemeProvider(); final Credentials jaasCreds = new JaasCredentials(); credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.SPNEGO), jaasCreds); credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.NTLM), new NTCredentials("Guest", "Guest", "Guest", "Guest")); final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider> create() .register(AuthSchemes.SPNEGO, nsf).register(AuthSchemes.NTLM, new NTLMSchemeFactory()).build(); hcb.setDefaultAuthSchemeRegistry(authSchemeRegistry); } hcb.setDefaultCredentialsProvider(credsProvider); hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(10 * 1000).build()); final CloseableHttpClient httpClient = hcb.build(); return httpClient; }
/** * Sharepoint requires NTLM. This client requires a non-null user/passwd/domain. * */ @Override public HttpClient getClient() { if (currentConn!=null){ return currentConn; } HttpClientBuilder clientHelper = HttpClientBuilder.create(); if (proxyHost != null) { clientHelper.setProxy(proxyHost); } RequestConfig globalConfig = RequestConfig.custom() .setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build(); CredentialsProvider creds = new BasicCredentialsProvider(); creds.setCredentials(AuthScope.ANY, new NTCredentials(user, passwd, server, domain)); clientHelper.setDefaultCredentialsProvider(creds); HttpClient httpClient = clientHelper.setDefaultRequestConfig(globalConfig).build(); return httpClient; }
public void configure() throws ConfigurationException { super.configure(); HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, getTimeout()); HttpConnectionParams.setSoTimeout(httpParameters, getTimeout()); httpClient = new DefaultHttpClient(connectionManager, httpParameters); httpClient.getAuthSchemes().register("NTLM", new NTLMSchemeFactory()); CredentialFactory cf = new CredentialFactory(getAuthAlias(), getUserName(), getPassword()); httpClient.getCredentialsProvider().setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new NTCredentials(cf.getUsername(), cf.getPassword(), Misc .getHostname(), getAuthDomain())); if (StringUtils.isNotEmpty(getProxyHost())) { HttpHost proxy = new HttpHost(getProxyHost(), getProxyPort()); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } }
private static void buildClient() { if ( USE_PROXY ) { ClientConfig config = new ClientConfig(); config.connectorProvider(new ApacheConnectorProvider()); CredentialsProvider credentials = new BasicCredentialsProvider(); credentials.setCredentials(AuthScope.ANY, new NTCredentials(PROXY_USER, PROXY_PASS, null, PROXY_DOMAIN)); config.property(ApacheClientProperties.CREDENTIALS_PROVIDER, credentials); config.property(ClientProperties.PROXY_URI, PROXY_PROTOCOL + PROXY_SERVER); client = ClientBuilder.newClient(config); } else client = ClientBuilder.newClient(); }
@Override public Queue<AuthOption> select(final Map<String, Header> challenges, final HttpHost authhost, final HttpResponse response, final HttpContext context) throws MalformedChallengeException { final HttpClientContext clientContext = HttpClientContext.adapt(context); final Queue<AuthOption> options = new LinkedList<AuthOption>(); final Lookup<AuthSchemeProvider> registry = clientContext.getAuthSchemeRegistry(); if(registry == null) { return options; } final RequestConfig config = clientContext.getRequestConfig(); Collection<String> authPrefs = config.getProxyPreferredAuthSchemes(); if(authPrefs == null) { authPrefs = DEFAULT_SCHEME_PRIORITY; } if(log.isDebugEnabled()) { log.debug("Authentication schemes in the order of preference: " + authPrefs); } for(final String id : authPrefs) { final Header challenge = challenges.get(id.toLowerCase(Locale.ROOT)); if(challenge != null) { final AuthSchemeProvider authSchemeProvider = registry.lookup(id); if(authSchemeProvider == null) { continue; } final AuthScheme authScheme = authSchemeProvider.create(context); authScheme.processChallenge(challenge); final Credentials saved = keychain.getCredentials(authhost.getHostName()); if(StringUtils.isEmpty(saved.getPassword())) { try { final Credentials input = prompt.prompt(bookmark, StringUtils.EMPTY, String.format("%s %s", LocaleFactory.localizedString("Login", "Login"), authhost.getHostName()), authScheme.getRealm(), new LoginOptions() .icon(bookmark.getProtocol().disk()) .usernamePlaceholder(LocaleFactory.localizedString("Username", "Credentials")) .passwordPlaceholder(LocaleFactory.localizedString("Password", "Credentials")) .user(true).password(true) ); if(input.isSaved()) { context.setAttribute(PROXY_CREDENTIALS_INPUT_ID, input); } options.add(new AuthOption(authScheme, new NTCredentials(input.getUsername(), input.getPassword(), preferences.getProperty("webdav.ntlm.workstation"), preferences.getProperty("webdav.ntlm.domain")))); } catch(LoginCanceledException ignored) { // Ignore dismiss of prompt throw new MalformedChallengeException(ignored.getMessage(), ignored); } } else { options.add(new AuthOption(authScheme, new NTCredentials(saved.getUsername(), saved.getPassword(), preferences.getProperty("webdav.ntlm.workstation"), preferences.getProperty("webdav.ntlm.domain")))); } } else { if(log.isDebugEnabled()) { log.debug("Challenge for " + id + " authentication scheme not available"); // Try again } } } return options; }
/** * Returns a new instance of NTCredentials used for proxy authentication. */ private static Credentials newNtCredentials(ProxyConfiguration proxyConfiguration) { return new NTCredentials(proxyConfiguration.username(), proxyConfiguration.password(), proxyConfiguration.ntlmWorkstation(), proxyConfiguration.ntlmDomain()); }
/** * Returns a new instance of NTCredentials used for proxy authentication. */ private static Credentials newNTCredentials(HttpClientSettings settings) { return new NTCredentials(settings.getProxyUsername(), settings.getProxyPassword(), settings.getProxyWorkstation(), settings.getProxyDomain()); }
public Credentials getCredentials(final AuthScope authscope) { Args.notNull(authscope, "Auth scope"); final Credentials localcreds = internal.getCredentials(authscope); if (localcreds != null) { return localcreds; } if (authscope.getHost() != null) { PasswordAuthentication systemcreds = getSystemCreds( authscope, Authenticator.RequestorType.SERVER); if (systemcreds == null) { systemcreds = getSystemCreds( authscope, Authenticator.RequestorType.PROXY); } if (systemcreds != null) { final String domain = System.getProperty("http.auth.ntlm.domain"); if (domain != null) { return new NTCredentials( systemcreds.getUserName(), new String(systemcreds.getPassword()), null, domain); } else { if (AuthSchemes.NTLM.equalsIgnoreCase(authscope.getScheme())) { // Domian may be specified in a fully qualified user name return new NTCredentials( systemcreds.getUserName(), new String(systemcreds.getPassword()), null, null); } else { return new UsernamePasswordCredentials( systemcreds.getUserName(), new String(systemcreds.getPassword())); } } } } return null; }
public CloseableHttpAsyncClient createHttpAsyncClient( ClientConfiguration config, PoolingNHttpClientConnectionManager cm) { HttpAsyncClientBuilder httpClientBuilder = HttpAsyncClients.custom(); httpClientBuilder.setConnectionManager(cm); RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(config.getConnectionTimeoutInMillisecond()) .setSocketTimeout(config.getSocketTimeoutInMillisecond()).build(); httpClientBuilder.setDefaultRequestConfig(requestConfig); httpClientBuilder.setUserAgent(config.getUserAgent()); httpClientBuilder.disableCookieManagement(); String proxyHost = config.getProxyHost(); int proxyPort = config.getProxyPort(); if (proxyHost != null) { if (proxyPort <= 0) { throw new ClientException("The proxy port is invalid. Please check your configuration."); } HttpHost proxy = new HttpHost(proxyHost, proxyPort); httpClientBuilder.setProxy(proxy); String proxyUsername = config.getProxyUsername(); String proxyPassword = config.getProxyPassword(); if (proxyUsername != null && proxyPassword != null) { String proxyDomain = config.getProxyDomain(); String proxyWorkstation = config.getProxyWorkstation(); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope(proxyHost, proxyPort), new NTCredentials( proxyUsername, proxyPassword, proxyWorkstation, proxyDomain)); httpClientBuilder.setDefaultCredentialsProvider(credsProvider); } } return httpClientBuilder.build(); }
public RawClient(@NotNull final Config config, @Nullable ConnectionService connectionService) { this.config = config; this.connectionService = connectionService; HttpClientBuilder httpBuilder = HttpClientBuilder.create(); requestConfigBuilder = RequestConfig.custom(); CredentialsProvider provider = new BasicCredentialsProvider(); String buildVersion = null; try { Properties buildProperties = new Properties(); InputStream in = getClass().getResourceAsStream("/com/samebug/clients/http/build.properties"); buildProperties.load(in); in.close(); buildVersion = buildProperties.getProperty("version"); } catch (Exception ignored) { } final String myUserAgent = buildVersion != null ? "Samebug-HttpClient/" + buildVersion : "Samebug-HttpClient"; requestConfigBuilder.setConnectTimeout(config.connectTimeout).setSocketTimeout(config.requestTimeout).setConnectionRequestTimeout(500); final ProxyConfig proxySettings = config.proxy; if (proxySettings != null && proxySettings.host != null && !proxySettings.host.isEmpty()) { requestConfigBuilder.setProxy(new HttpHost(proxySettings.host, proxySettings.port)); if (proxySettings.login != null && proxySettings.password != null) { provider.setCredentials(new AuthScope(proxySettings.host, proxySettings.port, AuthScope.ANY_REALM, AuthSchemes.NTLM), new NTCredentials(proxySettings.login, proxySettings.password, null, null)); provider.setCredentials(new AuthScope(proxySettings.host, proxySettings.port), new UsernamePasswordCredentials(proxySettings.login, proxySettings.password)); } } defaultRequestConfig = requestConfigBuilder.build(); trackingConfig = requestConfigBuilder.setSocketTimeout(TrackingRequestTimeout_Millis).build(); List<BasicHeader> defaultHeaders = new ArrayList<BasicHeader>(); defaultHeaders.add(new BasicHeader("User-Agent", config.appUserAgent + " " + myUserAgent)); httpClient = httpBuilder.setDefaultRequestConfig(defaultRequestConfig) .setMaxConnTotal(MaxConnections).setMaxConnPerRoute(MaxConnections) .setDefaultCredentialsProvider(provider) .setDefaultHeaders(defaultHeaders) .build(); }
/** * @deprecated To be removed in IDEA 16. Use corresponding method of IdeHttpClientHelpers. */ @Deprecated @NotNull public CredentialsProvider setProxyCredentials(@NotNull CredentialsProvider provider) { if (USE_HTTP_PROXY && PROXY_AUTHENTICATION) { String ntlmUserPassword = PROXY_LOGIN.replace('\\', '/') + ":" + getPlainProxyPassword(); provider.setCredentials(new AuthScope(PROXY_HOST, PROXY_PORT, AuthScope.ANY_REALM, AuthSchemes.NTLM), new NTCredentials(ntlmUserPassword)); provider.setCredentials(new AuthScope(PROXY_HOST, PROXY_PORT), new UsernamePasswordCredentials(PROXY_LOGIN, getPlainProxyPassword())); } return provider; }
/** * Install credentials for IDE-wide proxy if usage of proxy and proxy authentication were enabled in {@link HttpConfigurable}. * * @param provider HttpClient's credentials provider used to configure new client * @see #setProxyCredentialsForUrlIfEnabled(CredentialsProvider, String) */ public static void setProxyCredentialsIfEnabled(@NotNull CredentialsProvider provider) { if (isHttpProxyEnabled() && isProxyAuthenticationEnabled()) { final String ntlmUserPassword = getProxyLogin().replace('\\', '/') + ":" + getProxyPassword(); provider.setCredentials(new AuthScope(getProxyHost(), getProxyPort(), AuthScope.ANY_REALM, AuthSchemes.NTLM), new NTCredentials(ntlmUserPassword)); provider.setCredentials(new AuthScope(getProxyHost(), getProxyPort()), new UsernamePasswordCredentials(getProxyLogin(), getProxyPassword())); } }
@Override public Credentials getCredentials(final AuthScope authscope) { Args.notNull(authscope, "Auth scope"); final Credentials localcreds = internal.getCredentials(authscope); if (localcreds != null) { return localcreds; } if (authscope.getHost() != null) { PasswordAuthentication systemcreds = getSystemCreds( authscope, Authenticator.RequestorType.SERVER); if (systemcreds == null) { systemcreds = getSystemCreds( authscope, Authenticator.RequestorType.PROXY); } if (systemcreds != null) { final String domain = System.getProperty("http.auth.ntlm.domain"); if (domain != null) { return new NTCredentials( systemcreds.getUserName(), new String(systemcreds.getPassword()), null, domain); } else { if (AuthSchemes.NTLM.equalsIgnoreCase(authscope.getScheme())) { // Domian may be specified in a fully qualified user name return new NTCredentials( systemcreds.getUserName(), new String(systemcreds.getPassword()), null, null); } else { return new UsernamePasswordCredentials( systemcreds.getUserName(), new String(systemcreds.getPassword())); } } } } return null; }
@Test public void testProxyCredentialsScope() throws Exception { HttpClient wdmClient = new HttpClient.Builder().proxy("myproxy:8081") .proxyUser("domain\\me").proxyPass("pass").build(); Field field = HttpClient.class.getDeclaredField("closeableHttpClient"); field.setAccessible(true); CloseableHttpClient client = (CloseableHttpClient) field.get(wdmClient); field = client.getClass().getDeclaredField("credentialsProvider"); field.setAccessible(true); BasicCredentialsProvider provider = (BasicCredentialsProvider) field .get(client); assertThat( provider.getCredentials( new AuthScope(ANY_HOST, ANY_PORT, ANY_REALM, NTLM)), instanceOf(NTCredentials.class)); assertThat( provider.getCredentials( new AuthScope(ANY_HOST, ANY_PORT, ANY_REALM, BASIC)), instanceOf(UsernamePasswordCredentials.class)); assertThat(provider.getCredentials(new AuthScope(ANY_HOST, ANY_PORT)), instanceOf(UsernamePasswordCredentials.class)); assertThat( provider.getCredentials( new AuthScope(ANY_HOST, ANY_PORT, ANY_REALM, KERBEROS)), instanceOf(UsernamePasswordCredentials.class)); }
/** * Returns an NTCredentials object for given username and password * * @param userName * @param password * @return */ public static NTCredentials getNTCredentials(final String userName, final String password) { assert userName != null; assert password != null; String user = userName; String domain = ""; final String workstation = SystemHelper.getComputerName(); // If the username has a backslash, then the domain is the first part and the username is the second part if (userName.contains("\\")) { String[] parts = userName.split("[\\\\]"); if (parts.length == 2) { domain = parts[0]; user = parts[1]; } } else if (userName.contains("/")) { // If the username has a slash, then the domain is the first part and the username is the second part String[] parts = userName.split("[/]"); if (parts.length == 2) { domain = parts[0]; user = parts[1]; } } else if (userName.contains("@")) { // If the username has an asterisk, then the domain is the second part and the username is the first part String[] parts = userName.split("[@]"); if (parts.length == 2) { user = parts[0]; domain = parts[1]; } } return new org.apache.http.auth.NTCredentials(user, password, workstation, domain); }
private void createAndVerifyNTCredentials(final String domain, final String name, final String domainName, final String pass) { final AuthenticationInfo info = new AuthenticationInfo(domainName, pass, "server", "display"); final Credentials credentials = AuthHelper.getCredentials(ServerContext.Type.TFS, info); Assert.assertTrue(credentials instanceof NTCredentials); Assert.assertEquals(name, ((NTCredentials) credentials).getUserName()); Assert.assertEquals(domain, ((NTCredentials) credentials).getDomain().toLowerCase()); if(SystemHelper.getComputerName() != null) { //coming back null when running from command line on Mac, works inside IDE Assert.assertEquals(SystemHelper.getComputerName().toLowerCase(), ((NTCredentials) credentials).getWorkstation().toLowerCase()); } Assert.assertEquals(pass, credentials.getPassword()); }
@Override public void addAuth(AuthCredentials creds) { String host = (StringUtils.isBlank(creds.getHost()) || "*".equals(creds.getHost())) ? AuthScope.ANY_HOST : creds.getHost(); String realm = (StringUtils.isBlank(creds.getRealm()) || "*".equals(creds.getRealm())) ? AuthScope.ANY_REALM : creds.getRealm(); int port = NumberUtils.toInt(creds.getPortString(), AuthScope.ANY_PORT); String scheme = creds.getScheme() != null ? creds.getScheme().getRepresentation() : AuthScope.ANY_SCHEME; AuthScope scope = new AuthScope(host, port, realm, scheme); if (AuthScheme.NTLM == creds.getScheme()) { context.getCredentialsProvider().setCredentials(scope, new NTCredentials(creds.getUserName(), creds.getPassword(), "tank-test", creds.getRealm())); } else { context.getCredentialsProvider().setCredentials(scope, new UsernamePasswordCredentials(creds.getUserName(), creds.getPassword())); } }
public static void setNTCredentials(DefaultHttpClient client, String username,String password, String workStation, String domain) { // set Username and Password if(!StringUtil.isEmpty(username,true)) { if(password==null)password=""; CredentialsProvider cp = client.getCredentialsProvider(); cp.setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new NTCredentials(username,password,workStation,domain)); //httpMethod.setDoAuthentication( true ); } }
public static void setNTCredentials(HttpClientBuilder builder, String username,String password, String workStation, String domain) { // set Username and Password if(!StringUtil.isEmpty(username,true)) { if(password==null)password=""; CredentialsProvider cp = new BasicCredentialsProvider(); builder.setDefaultCredentialsProvider(cp); cp.setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new NTCredentials(username,password,workStation,domain)); } }
private static Credentials createCredentials(final String username, final String password) { final String user; final String domain; int backslashIndex = username.indexOf('\\'); if (backslashIndex >= 0) { user = username.substring(backslashIndex + 1); domain = username.substring(0, backslashIndex); } else { user = username; domain = System.getProperty("http.auth.ntlm.domain", ""); } return new NTCredentials(user, password, HostUtil.getLocalHostName(), domain); }
private static HttpClient createProxyEnabledHttpClient() { String USERNAME = proxyUser; // username for proxy authentication String PASSWORD = proxyPass; // password for proxy authentication String PROXY_ADDRESS = "proxy.hs-karlsruhe.de"; // proxy (IP) address String PROXY_DOMAIN = "http"; // proxy domain HttpHost proxy = new HttpHost(PROXY_ADDRESS, 8888); DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); AuthCache authCache = new BasicAuthCache(); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(PROXY_ADDRESS, 8888), new NTCredentials(USERNAME, PASSWORD, "", PROXY_DOMAIN)); HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credsProvider); context.setAuthCache(authCache); //String token = USERNAME + ":" + PASSWORD; //String auth = "Basic " + String.valueOf(Base64.encode(token.getBytes())); // TODO add headers to the request //request.addHeader("Proxy-Authorization", auth); //request.addHeader("Https-Proxy-Authorization", auth); RequestConfig defaultRequestConfig = RequestConfig.custom() .setSocketTimeout(5000) .setConnectTimeout(5000) .setConnectionRequestTimeout(5000) .setStaleConnectionCheckEnabled(true) .build(); //Main client about to connect CloseableHttpClient httpclient = HttpClients.custom() .setDefaultCredentialsProvider(credsProvider) .setRoutePlanner(routePlanner) .setDefaultRequestConfig(defaultRequestConfig) .build(); return httpclient; }
@Override public DefaultHttpClient create(final HttpMethod method, final URI uri) { final DefaultHttpClient httpclient = super.create(method, uri); final CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new NTCredentials(username, password, workstation, domain)); httpclient.setCredentialsProvider(credsProvider); return httpclient; }
/** * Constructs a new BCE client using the specified client configuration options (ex: max retry attempts, proxy * settings, etc), and request metric collector. * * @param config Configuration options specifying how this client will communicate with BCE (ex: proxy settings, * retry count, etc.). * @param signer signer used to sign http requests * @throws java.lang.IllegalArgumentException If config or signer is null. */ public BceHttpClient(BceClientConfiguration config, Signer signer) { checkNotNull(config, "config should not be null."); checkNotNull(signer, "signer should not be null."); this.config = config; this.signer = signer; this.connectionManager = this.createHttpClientConnectionManager(); this.httpClient = this.createHttpClient(this.connectionManager); IdleConnectionReaper.registerConnectionManager(this.connectionManager); this.requestConfigBuilder = RequestConfig.custom(); this.requestConfigBuilder.setConnectTimeout(config.getConnectionTimeoutInMillis()); this.requestConfigBuilder.setStaleConnectionCheckEnabled(true); if (config.getLocalAddress() != null) { this.requestConfigBuilder.setLocalAddress(config.getLocalAddress()); } String proxyHost = config.getProxyHost(); int proxyPort = config.getProxyPort(); if (proxyHost != null && proxyPort > 0) { this.proxyHttpHost = new HttpHost(proxyHost, proxyPort); this.requestConfigBuilder.setProxy(this.proxyHttpHost); this.credentialsProvider = new BasicCredentialsProvider(); String proxyUsername = config.getProxyUsername(); String proxyPassword = config.getProxyPassword(); String proxyDomain = config.getProxyDomain(); String proxyWorkstation = config.getProxyWorkstation(); if (proxyUsername != null && proxyPassword != null) { this.credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain)); } } }
/** * Create a new instance of the {@code HttpClientMessageSender} with a default {@link HttpClient} * with added support for NTLM. * * @param ntlmUsername the NTLM username (without domain name) * @param ntlmPassword the NTLM password * @param ntlmDomain the NTLM domain */ public NtlmCloseableHttpComponentsMessageSender(String ntlmUsername, String ntlmPassword, String ntlmDomain) { super(); Assert.hasText(ntlmUsername, "the ntlmUsername must not be empty"); Assert.hasText(ntlmPassword, "the ntlmPassword must not be empty"); Assert.hasText(ntlmDomain, "the ntlmDomain must not be empty"); this.ntlmUsername = ntlmUsername; this.ntlmPassword = ntlmPassword; this.ntlmDomain = ntlmDomain; // Register NTLMSchemeFactory with the HttpClient instance you want to NTLM enable. Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.NTLM, new NTLMSchemeFactory()) .build(); getClientBuilder().setDefaultAuthSchemeRegistry(authSchemeRegistry); NTCredentials credentials = new NTCredentials(ntlmUsername, ntlmPassword, MACHINE_NAME, ntlmDomain); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); setCredentials(credentials); credentialsProvider.setCredentials(AuthScope.ANY, credentials); // register NTLM to HttpClient setCredentialsProvider(credentialsProvider); }
@Test public void createNtlmCredentialsProvider() { CredentialsProvider credentialsProvider = getCredentialsProvider(AuthSchemes.NTLM); Credentials credentials = credentialsProvider.getCredentials(new AuthScope("host", 80)); assertThat(credentials, instanceOf(NTCredentials.class)); NTCredentials ntCredentials = (NTCredentials) credentials; assertEquals("DOMAIN", ntCredentials.getDomain()); assertEquals("HOST", ntCredentials.getWorkstation()); assertEquals("pass", ntCredentials.getPassword()); Credentials proxyCredentials = credentialsProvider.getCredentials(new AuthScope("proxy", 8080)); assertThat(proxyCredentials, instanceOf(UsernamePasswordCredentials.class)); UsernamePasswordCredentials userCredentials = (UsernamePasswordCredentials) proxyCredentials; assertEquals("proxyUsername", userCredentials.getUserName()); }