Example usage for org.apache.http.auth NTCredentials NTCredentials

List of usage examples for org.apache.http.auth NTCredentials NTCredentials

Introduction

In this page you can find the example usage for org.apache.http.auth NTCredentials NTCredentials.

Prototype

public NTCredentials(final String userName, final String password, final String workstation,
        final String domain) 

Source Link

Document

Constructor.

Usage

From source file:org.sonatype.nexus.apachehttpclient.Hc4ProviderBase.java

protected void applyAuthenticationConfig(final Builder builder, final RemoteAuthenticationSettings ras,
        final HttpHost proxyHost) {
    if (ras != null) {
        String authScope = "target";
        if (proxyHost != null) {
            authScope = proxyHost.toHostString() + " proxy";
        }//w w  w  .  ja  v a2 s  .c o  m

        final List<String> authorisationPreference = Lists.newArrayListWithExpectedSize(3);
        authorisationPreference.add(AuthSchemes.DIGEST);
        authorisationPreference.add(AuthSchemes.BASIC);
        Credentials credentials = null;
        if (ras instanceof ClientSSLRemoteAuthenticationSettings) {
            throw new IllegalArgumentException("SSL client authentication not yet supported!");
        } else if (ras instanceof NtlmRemoteAuthenticationSettings) {
            final NtlmRemoteAuthenticationSettings nras = (NtlmRemoteAuthenticationSettings) ras;
            // Using NTLM auth, adding it as first in policies
            authorisationPreference.add(0, AuthSchemes.NTLM);
            log.debug("{} authentication setup for NTLM domain '{}'", authScope, nras.getNtlmDomain());
            credentials = new NTCredentials(nras.getUsername(), nras.getPassword(), nras.getNtlmHost(),
                    nras.getNtlmDomain());
        } else if (ras instanceof UsernamePasswordRemoteAuthenticationSettings) {
            final UsernamePasswordRemoteAuthenticationSettings uras = (UsernamePasswordRemoteAuthenticationSettings) ras;
            log.debug("{} authentication setup for remote storage with username '{}'", authScope,
                    uras.getUsername());
            credentials = new UsernamePasswordCredentials(uras.getUsername(), uras.getPassword());
        }

        if (credentials != null) {
            if (proxyHost != null) {
                builder.setCredentials(new AuthScope(proxyHost), credentials);
                builder.getRequestConfigBuilder().setProxyPreferredAuthSchemes(authorisationPreference);
            } else {
                builder.setCredentials(AuthScope.ANY, credentials);
                builder.getRequestConfigBuilder().setTargetPreferredAuthSchemes(authorisationPreference);
            }
        }
    }
}

From source file:org.freaknet.gtrends.client.CmdLineParser.java

/**
 * Gets the <code>Credentials</code> for proxy authentication.
 *
 * @return credentials//w  ww  . j a va2 s.  com
 */
public Credentials getProxyCredentials() {
    String c = cmd.getOptionValue("C");
    Credentials credentials;
    Pattern pattern = Pattern.compile(".*" + DOMAIN_SEP + ".*" + USER_PASS_SEP);
    Matcher matcher = pattern.matcher(c);
    if (matcher.find()) {
        try {
            credentials = new NTCredentials(getProxyUsername(), getProxyPassword(),
                    InetAddress.getLocalHost().getHostName(), getProxyUserDomain());
        } catch (UnknownHostException ex) {

            Logger.getLogger(GoogleConfigurator.getLoggerPrefix()).log(Level.WARNING,
                    "Could not retrieve workstation name. Trying authentication without it.", ex);
            credentials = new NTCredentials(getProxyUsername(), getProxyPassword(), "", getProxyUserDomain());
        }
    } else {
        credentials = new UsernamePasswordCredentials(getProxyUsername(), getProxyPassword());
    }

    return credentials;
}

From source file:com.github.sardine.impl.SardineImpl.java

private CredentialsProvider getCredentialsProvider(String username, String password, String domain,
        String workstation) {//from w  ww. j  a v  a  2 s  . c om
    CredentialsProvider provider = new BasicCredentialsProvider();
    if (username != null) {
        provider.setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthPolicy.NTLM),
                new NTCredentials(username, password, workstation, domain));
        provider.setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthPolicy.BASIC),
                new UsernamePasswordCredentials(username, password));
        provider.setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthPolicy.DIGEST),
                new UsernamePasswordCredentials(username, password));
        provider.setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthPolicy.SPNEGO),
                new UsernamePasswordCredentials(username, password));
        provider.setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthPolicy.KERBEROS),
                new UsernamePasswordCredentials(username, password));
    }
    return provider;
}

From source file:org.sonatype.nexus.httpclient.config.ConfigurationCustomizer.java

/**
 * Apply authentication configuration to plan.
 *//* w ww. ja  v  a  2 s . c o  m*/
private void apply(final AuthenticationConfiguration authentication, final HttpClientPlan plan,
        @Nullable final HttpHost proxyHost) {
    Credentials credentials;
    List<String> authSchemes;

    if (authentication instanceof UsernameAuthenticationConfiguration) {
        UsernameAuthenticationConfiguration auth = (UsernameAuthenticationConfiguration) authentication;
        authSchemes = ImmutableList.of(DIGEST, BASIC);
        credentials = new UsernamePasswordCredentials(auth.getUsername(), auth.getPassword());
    } else if (authentication instanceof NtlmAuthenticationConfiguration) {
        NtlmAuthenticationConfiguration auth = (NtlmAuthenticationConfiguration) authentication;
        authSchemes = ImmutableList.of(NTLM, DIGEST, BASIC);
        credentials = new NTCredentials(auth.getUsername(), auth.getPassword(), auth.getHost(),
                auth.getDomain());
    } else {
        throw new IllegalArgumentException("Unsupported authentication configuration: " + authentication);
    }

    if (proxyHost != null) {
        plan.addCredentials(new AuthScope(proxyHost), credentials);
        plan.getRequest().setProxyPreferredAuthSchemes(authSchemes);
    } else {
        plan.addCredentials(AuthScope.ANY, credentials);
        plan.getRequest().setTargetPreferredAuthSchemes(authSchemes);
    }
}

From source file:fr.ippon.wip.http.hc.HttpClientExecutor.java

/**
 * This method updates the CredentialsProvider associated to the current
 * PortletSession and the windowID with the provided login and password.
 * Basic and NTLM authentication schemes are supported. This method uses the
 * current fr.ippon.wip.state.PortletWindow to retrieve the authentication
 * schemes requested by remote server.//w ww.j  av  a 2  s. co m
 * 
 * @param login
 * @param password
 * @param portletRequest
 *            Used to get current javax.portlet.PortletSession and windowID
 */
public void login(String login, String password, PortletRequest portletRequest) {
    HttpClientResourceManager resourceManager = HttpClientResourceManager.getInstance();
    CredentialsProvider credentialsProvider = resourceManager.getCredentialsProvider(portletRequest);
    PortletWindow portletWindow = PortletWindow.getInstance(portletRequest);
    List<String> schemes = portletWindow.getRequestedAuthSchemes();

    if (schemes.contains("Basic")) {
        // Creating basic credentials
        AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, "Basic");
        Credentials credentials = new UsernamePasswordCredentials(login, password);
        credentialsProvider.setCredentials(scope, credentials);
    }
    if (schemes.contains("NTLM")) {
        // Creating ntlm credentials
        AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, "NTLM");
        Credentials credentials = new NTCredentials(login, password, "", "");
        credentialsProvider.setCredentials(scope, credentials);
    }
}

From source file:org.dcache.srm.client.HttpClientSender.java

/**
 * Creates the HttpContext for a particular call to a SOAP server.
 *
 * Called once per session./*ww  w .  ja va2s.  com*/
 */
protected HttpClientContext createHttpContext(MessageContext msgContext, URI uri) {
    HttpClientContext context = new HttpClientContext(new BasicHttpContext());
    // if UserID is not part of the context, but is in the URL, use
    // the one in the URL.
    String userID = msgContext.getUsername();
    String passwd = msgContext.getPassword();
    if ((userID == null) && (uri.getUserInfo() != null)) {
        String info = uri.getUserInfo();
        int sep = info.indexOf(':');
        if ((sep >= 0) && (sep + 1 < info.length())) {
            userID = info.substring(0, sep);
            passwd = info.substring(sep + 1);
        } else {
            userID = info;
        }
    }
    if (userID != null) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        // if the username is in the form "user\domain"
        // then use NTCredentials instead.
        int domainIndex = userID.indexOf('\\');
        if (domainIndex > 0 && userID.length() > domainIndex + 1) {
            String domain = userID.substring(0, domainIndex);
            String user = userID.substring(domainIndex + 1);
            credsProvider.setCredentials(AuthScope.ANY,
                    new NTCredentials(user, passwd, NetworkUtils.getLocalHostname(), domain));
        } else {
            credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userID, passwd));
        }
        context.setCredentialsProvider(credsProvider);
    }
    context.setAttribute(HttpClientTransport.TRANSPORT_HTTP_CREDENTIALS,
            msgContext.getProperty(HttpClientTransport.TRANSPORT_HTTP_CREDENTIALS));
    return context;
}

From source file:com.github.lpezet.antiope.dao.DefaultHttpClientFactory.java

@Override
public HttpClient createHttpClient(APIConfiguration pConfiguration) {

    // Use a custom connection factory to customize the process of
    // initialization of outgoing HTTP connections. Beside standard connection
    // configuration parameters HTTP connection factory can define message
    // parser / writer routines to be employed by individual connections.
    HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> oConnFactory = new ManagedHttpClientConnectionFactory(
            new DefaultHttpRequestWriterFactory(), new DefaultHttpResponseParserFactory());

    SSLContext oSslContext = null;
    X509HostnameVerifier oHostnameVerifier = null;
    if (pConfiguration.isCheckSSLCertificates()) {
        oSslContext = SSLContexts.createSystemDefault();
        oHostnameVerifier = new BrowserCompatHostnameVerifier();
    } else {/*from w  ww.j  a v  a2s .c  o m*/
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(final X509Certificate[] chain, final String authType) {
            }

            @Override
            public void checkServerTrusted(final X509Certificate[] chain, final String authType) {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };

        // Install the all-trusting trust manager
        try {
            final SSLContext sslContext = SSLContext.getInstance(SSL);
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            // Create an ssl socket factory with our all-trusting manager
            //final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            oSslContext = sslContext;
        } catch (NoSuchAlgorithmException e) {
            throw new APIClientException(e);
        } catch (KeyManagementException e) {
            throw new APIClientException(e);
        }
        oHostnameVerifier = new AllowAllHostnameVerifier();
    }

    // Create a registry of custom connection socket factories for supported
    // protocol schemes.
    Registry<ConnectionSocketFactory> oSocketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register(HTTP, PlainConnectionSocketFactory.INSTANCE)
            .register(HTTPS, new SSLConnectionSocketFactory(oSslContext, oHostnameVerifier)).build();

    // Use custom DNS resolver to override the system DNS resolution.
    DnsResolver oDnsResolver = new SystemDefaultDnsResolver(); /* {
                                                               @Override
                                                               public InetAddress[] resolve(final String host) throws UnknownHostException {
                                                               if (host.equalsIgnoreCase("myhost")) {
                                                               return new InetAddress[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }) };
                                                               } else {
                                                               return super.resolve(host);
                                                               }
                                                               }
                                                               };*/

    // Create a connection manager with custom configuration.
    PoolingHttpClientConnectionManager oConnManager = new PoolingHttpClientConnectionManager(
            oSocketFactoryRegistry, oConnFactory, oDnsResolver);

    // Create socket configuration
    SocketConfig oSocketConfig = SocketConfig.custom().setTcpNoDelay(true)
            .setSoTimeout(pConfiguration.getSocketTimeout()).build();

    // Configure the connection manager to use socket configuration either
    // by default or for a specific host.
    oConnManager.setDefaultSocketConfig(oSocketConfig);
    // connManager.setSocketConfig(new HttpHost("somehost", 80), oSocketConfig);

    // Create message constraints
    MessageConstraints oMessageConstraints = MessageConstraints.custom().setMaxHeaderCount(200)
            .setMaxLineLength(2000).build();
    // Create connection configuration
    ConnectionConfig oConnectionConfig = ConnectionConfig.custom()
            .setMalformedInputAction(CodingErrorAction.IGNORE)
            .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8)
            .setMessageConstraints(oMessageConstraints).build();
    // Configure the connection manager to use connection configuration either
    // by default or for a specific host.
    oConnManager.setDefaultConnectionConfig(oConnectionConfig);
    // connManager.setConnectionConfig(new HttpHost("somehost", 80), ConnectionConfig.DEFAULT);

    // Configure total max or per route limits for persistent connections
    // that can be kept in the pool or leased by the connection manager.
    oConnManager.setMaxTotal(100);
    oConnManager.setDefaultMaxPerRoute(10);
    //oConnManager.setMaxPerRoute(new HttpRoute(new HttpHost("somehost", 80)), 20);

    // Use custom cookie store if necessary.
    CookieStore oCookieStore = new BasicCookieStore();
    // Use custom credentials provider if necessary.
    //
    // Create global request configuration
    RequestConfig oDefaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH)
            //.setExpectContinueEnabled(true)         // WARNING: setting it to true slows things down by 4s!!!!
            .setStaleConnectionCheckEnabled(true)
            .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
            .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC))
            .setConnectTimeout(pConfiguration.getConnectionTimeout()).build();

    CredentialsProvider oCredentialsProvider = new BasicCredentialsProvider();
    HttpHost oProxy = null;

    if (pConfiguration.getProxyHost() != null && pConfiguration.getProxyPort() > 0) {
        String proxyHost = pConfiguration.getProxyHost();
        int proxyPort = pConfiguration.getProxyPort();
        String proxyUsername = pConfiguration.getProxyUsername();
        String proxyPassword = pConfiguration.getProxyPassword();
        String proxyDomain = pConfiguration.getProxyDomain();
        String proxyWorkstation = pConfiguration.getProxyWorkstation();

        oProxy = new HttpHost(proxyHost, proxyPort);

        if (proxyUsername != null && proxyPassword != null) {
            oCredentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                    new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain));
        }
    }

    // Create an HttpClient with the given custom dependencies and configuration.
    CloseableHttpClient oHttpClient = HttpClients.custom().setConnectionManager(oConnManager)
            .setDefaultCookieStore(oCookieStore).setDefaultCredentialsProvider(oCredentialsProvider)
            .setProxy(oProxy).setDefaultRequestConfig(oDefaultRequestConfig).build();

    return oHttpClient;
    /*
    RequestConfig oRequestConfig = RequestConfig.custom()
    .setConnectTimeout(pConfiguration.getConnectionTimeout())
    .setSocketTimeout(pConfiguration.getSocketTimeout())
    .setStaleConnectionCheckEnabled(true)
    .build();
    */
}

From source file:org.eclipse.mylyn.commons.http.HttpUtil.java

public static Credentials getHttpClientCredentials(AuthenticationCredentials credentials, String host) {
    String username = credentials.getUserName();
    String password = credentials.getPassword();
    int i = username.indexOf("\\"); //$NON-NLS-1$
    if (i > 0 && i < username.length() - 1 && host != null) {
        return new NTCredentials(username.substring(i + 1), password, host, username.substring(0, i));
    } else {//from  w ww . j a va 2 s . co  m
        return new UsernamePasswordCredentials(username, password);
    }
}

From source file:com.googlecode.sardine.impl.SardineImpl.java

/**
 * @param username//from   www . j  av  a  2  s  .co m
 *            Use in authentication header credentials
 * @param password
 *            Use in authentication header credentials
 * @param domain
 *            NTLM authentication
 * @param workstation
 *            NTLM authentication
 */
public void setCredentials(String username, String password, String domain, String workstation) {
    if (username != null) {
        this.client.getCredentialsProvider().setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthPolicy.NTLM),
                new NTCredentials(username, password, workstation, domain));
        this.client.getCredentialsProvider().setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthPolicy.BASIC),
                new UsernamePasswordCredentials(username, password));
        this.client.getCredentialsProvider().setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthPolicy.DIGEST),
                new UsernamePasswordCredentials(username, password));
    }
}

From source file:org.jasig.portlet.calendar.adapter.exchange.ExchangeCredentialsInitializationService.java

protected Credentials createNTCredentials(String ntlmDomain, String username, String password) {
    if (username == null) {
        throw new CalendarException(
                "Required user attribute username is null. Insure user-attribute user.login.id"
                        + " is present in the <user-attribute> section of portlet.xml");
    }//from   w  w  w . j a va 2  s .c  o m

    // For Exchange domain integration, only the username is applicable, not the domain name. This allows the
    // rare case of using the email address rather than loginId for the credentials.  If a domain is present
    // in the username remove the @domain part.
    int index = username.indexOf("@");
    username = index > 0 ? username.substring(0, index) : username;

    // construct a credentials object from the username and password
    return new NTCredentials(username, password, "paramDoesNotSeemToMatter", ntlmDomain);
}