Search in sources :

Example 71 with CredentialsProvider

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.CredentialsProvider in project zm-mailbox by Zimbra.

the class ExchangeFreeBusyProvider method basicAuth.

private boolean basicAuth(HttpClientBuilder clientBuilder, ServerInfo info) {
    Credentials cred = new UsernamePasswordCredentials(info.authUsername, info.authPassword);
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY, cred);
    clientBuilder.setDefaultCredentialsProvider(credsProvider);
    Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.BASIC, new BasicSchemeFactory(Consts.UTF_8)).build();
    clientBuilder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
    return true;
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) BasicSchemeFactory(org.apache.http.impl.auth.BasicSchemeFactory) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) AuthSchemeProvider(org.apache.http.auth.AuthSchemeProvider) Credentials(org.apache.http.auth.Credentials) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 72 with CredentialsProvider

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.CredentialsProvider in project zm-mailbox by Zimbra.

the class HttpProxyUtil method configureProxy.

public static synchronized void configureProxy(HttpClientBuilder clientBuilder) {
    try {
        String url = Provisioning.getInstance().getLocalServer().getAttr(Provisioning.A_zimbraHttpProxyURL, null);
        if (url == null)
            return;
        // need to initializae all the statics
        if (sProxyUrl == null || !sProxyUrl.equals(url)) {
            sProxyUrl = url;
            sProxyUri = new URI(url);
            sProxyAuthScope = null;
            sProxyCreds = null;
            String userInfo = sProxyUri.getUserInfo();
            if (userInfo != null) {
                int i = userInfo.indexOf(':');
                if (i != -1) {
                    sProxyAuthScope = new AuthScope(sProxyUri.getHost(), sProxyUri.getPort(), null);
                    sProxyCreds = new UsernamePasswordCredentials(userInfo.substring(0, i), userInfo.substring(i + 1));
                }
            }
        }
        if (ZimbraLog.misc.isDebugEnabled()) {
            ZimbraLog.misc.debug("setting proxy: " + url);
        }
        HttpHost proxy = new HttpHost(sProxyUri.getHost(), sProxyUri.getPort());
        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
        clientBuilder.setDefaultRequestConfig(config);
        if (sProxyAuthScope != null && sProxyCreds != null) {
            CredentialsProvider cred = new BasicCredentialsProvider();
            cred.setCredentials(sProxyAuthScope, sProxyCreds);
            clientBuilder.setDefaultCredentialsProvider(cred);
        }
    } catch (ServiceException e) {
        ZimbraLog.misc.warn("Unable to configureProxy: " + e.getMessage(), e);
    } catch (URISyntaxException e) {
        ZimbraLog.misc.warn("Unable to configureProxy: " + e.getMessage(), e);
    }
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) ServiceException(com.zimbra.common.service.ServiceException) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 73 with CredentialsProvider

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.CredentialsProvider in project zm-mailbox by Zimbra.

the class SoapHttpTransport method invoke.

public Element invoke(Element document, boolean raw, boolean noSession, String requestedAccountId, String changeToken, String tokenType, NotificationFormat nFormat, String curWaitSetID, ResponseHandler respHandler) throws IOException, ServiceException {
    HttpPost method = null;
    HttpClient client = null;
    try {
        // Assemble post method.  Append document name, so that the request
        // type is written to the access log.
        String uri = getUriWithPath(document);
        method = new HttpPost(uri);
        // Set user agent if it's specified.
        String agentName = getUserAgentName();
        if (agentName != null) {
            String agentVersion = getUserAgentVersion();
            if (agentVersion != null)
                agentName += " " + agentVersion;
            method.addHeader(new BasicHeader("User-Agent", agentName));
        }
        // Set the original user agent if it's specified.
        String originalUserAgent = getOriginalUserAgent();
        if (originalUserAgent != null) {
            method.addHeader(new BasicHeader(HeaderConstants.HTTP_HEADER_ORIG_USER_AGENT, originalUserAgent));
        }
        // the content-type charset will determine encoding used
        // when we set the request body
        method.addHeader("Content-Type", getRequestProtocol().getContentType());
        if (getClientIp() != null) {
            method.addHeader(RemoteIP.X_ORIGINATING_IP_HEADER, getClientIp());
            if (ZimbraLog.misc.isDebugEnabled()) {
                ZimbraLog.misc.debug("set remote IP header [%s] to [%s]", RemoteIP.X_ORIGINATING_IP_HEADER, getClientIp());
            }
        }
        Element soapReq = generateSoapMessage(document, raw, noSession, requestedAccountId, changeToken, tokenType, nFormat, curWaitSetID);
        String soapMessage = SoapProtocol.toString(soapReq, getPrettyPrint());
        method.setEntity(new StringEntity(soapMessage, ContentType.create(ContentType.APPLICATION_XML.getMimeType(), "UTF-8")));
        if (getRequestProtocol().hasSOAPActionHeader())
            method.addHeader("SOAPAction", mUri);
        if (mCustomHeaders != null) {
            for (Map.Entry<String, String> entry : mCustomHeaders.entrySet()) method.addHeader(entry.getKey(), entry.getValue());
        }
        String host = method.getURI().getHost();
        ZAuthToken zToken = getAuthToken();
        BasicCookieStore cookieStore = HttpClientUtil.newHttpState(zToken, host, this.isAdmin());
        String trustedToken = getTrustedToken();
        if (trustedToken != null) {
            BasicClientCookie cookie = new BasicClientCookie(ZimbraCookie.COOKIE_ZM_TRUST_TOKEN, trustedToken);
            cookie.setDomain(host);
            cookie.setPath("/");
            cookie.setSecure(false);
            cookieStore.addCookie(cookie);
        }
        if (zToken instanceof ZJWToken) {
            method.addHeader(Constants.AUTH_HEADER, Constants.BEARER + " " + zToken.getValue());
        }
        ZimbraLog.soap.trace("Httpclient timeout: %s", mTimeout);
        RequestConfig reqConfig = RequestConfig.custom().setCookieSpec(cookieStore.getCookies().size() == 0 ? CookieSpecs.IGNORE_COOKIES : CookieSpecs.BROWSER_COMPATIBILITY).setSocketTimeout(mTimeout).build();
        SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(mTimeout).setTcpNoDelay(LC.httpclient_external_connmgr_tcp_nodelay.booleanValue()).build();
        method.setProtocolVersion(HttpVersion.HTTP_1_1);
        method.addHeader("Connection", mKeepAlive ? "Keep-alive" : "Close");
        client = mClientBuilder.setDefaultRequestConfig(reqConfig).setDefaultSocketConfig(socketConfig).setDefaultCookieStore(cookieStore).build();
        ZimbraLog.soap.trace("Httpclient request config timeout: %s", reqConfig.getSocketTimeout());
        if (mHostConfig != null && mHostConfig.getUsername() != null && mHostConfig.getPassword() != null) {
            Credentials credentials = new UsernamePasswordCredentials(mHostConfig.getUsername(), mHostConfig.getPassword());
            AuthScope authScope = new AuthScope(null, -1);
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(authScope, credentials);
            client = HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).setDefaultRequestConfig(reqConfig).setDefaultSocketConfig(socketConfig).setDefaultCookieStore(cookieStore).build();
        }
        if (mHttpDebugListener != null) {
            mHttpDebugListener.sendSoapMessage(method, soapReq, cookieStore);
        }
        HttpResponse response = client.execute(method);
        int responseCode = response.getStatusLine().getStatusCode();
        // real server issues will probably be "503" or "404"
        if (responseCode != HttpServletResponse.SC_OK && responseCode != HttpServletResponse.SC_INTERNAL_SERVER_ERROR)
            throw ServiceException.PROXY_ERROR(response.getStatusLine().getReasonPhrase(), uri);
        // Read the response body.  Use the stream API instead of the byte[]
        // version to avoid HTTPClient whining about a large response.
        InputStreamReader reader = new InputStreamReader(response.getEntity().getContent(), SoapProtocol.getCharset());
        String responseStr = "";
        try {
            if (respHandler != null) {
                respHandler.process(reader);
                return null;
            } else {
                HttpEntity httpEntity = response.getEntity();
                httpEntity.getContentLength();
                responseStr = ByteUtil.getContent(reader, (int) httpEntity.getContentLength(), false);
                Element soapResp = parseSoapResponse(responseStr, raw);
                if (mHttpDebugListener != null) {
                    mHttpDebugListener.receiveSoapMessage(method, soapResp);
                }
                return soapResp;
            }
        } catch (SoapFaultException x) {
            // attach request/response to the exception and rethrow
            x.setFaultRequest(soapMessage);
            x.setFaultResponse(responseStr.substring(0, Math.min(10240, responseStr.length())));
            throw x;
        }
    } finally {
        // Release the connection to the connection manager
        if (method != null)
            method.releaseConnection();
        // exits.  Leave it here anyway.
        if (!mKeepAlive)
            ZimbraHttpConnectionManager.getInternalHttpConnMgr().closeIdleConnections();
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) RequestConfig(org.apache.http.client.config.RequestConfig) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) SocketConfig(org.apache.http.config.SocketConfig) InputStreamReader(java.io.InputStreamReader) HttpEntity(org.apache.http.HttpEntity) HttpResponse(org.apache.http.HttpResponse) BasicClientCookie(org.apache.http.impl.cookie.BasicClientCookie) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) ZAuthToken(com.zimbra.common.auth.ZAuthToken) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) StringEntity(org.apache.http.entity.StringEntity) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) ZJWToken(com.zimbra.common.auth.ZJWToken) HttpClient(org.apache.http.client.HttpClient) AuthScope(org.apache.http.auth.AuthScope) Map(java.util.Map) HashMap(java.util.HashMap) BasicHeader(org.apache.http.message.BasicHeader) Credentials(org.apache.http.auth.Credentials) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 74 with CredentialsProvider

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.CredentialsProvider in project wildfly by wildfly.

the class ConstraintDrivenAuthModeTestCase method testSecuredResourceWithValidCredential.

@Test
public void testSecuredResourceWithValidCredential() throws Exception {
    HttpGet request = new HttpGet(new URI(url.toExternalForm() + "secure.jsp"));
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user1", "password1");
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY, credentials);
    request.addHeader(new BasicScheme().authenticate(credentials, "UTF-8", false));
    try (CloseableHttpClient httpClient = HttpClients.custom().build()) {
        try (CloseableHttpResponse response = httpClient.execute(request)) {
            int statusCode = response.getStatusLine().getStatusCode();
            assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode);
            assertEquals("Unexpected content of HTTP response.", "user1", EntityUtils.toString(response.getEntity()));
        }
    }
}
Also used : BasicScheme(org.apache.http.impl.auth.BasicScheme) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpGet(org.apache.http.client.methods.HttpGet) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) URI(java.net.URI) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) Test(org.junit.Test)

Example 75 with CredentialsProvider

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.CredentialsProvider in project wildfly by wildfly.

the class ConstraintDrivenAuthModeTestCase method testUnsecureResourceWithInvalidCredential.

@Test
public void testUnsecureResourceWithInvalidCredential() throws Exception {
    HttpGet request = new HttpGet(new URI(url.toExternalForm() + "unsecure.jsp"));
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user1", "password2");
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY, credentials);
    request.addHeader(new BasicScheme().authenticate(credentials, request));
    try (CloseableHttpClient httpClient = HttpClients.custom().build()) {
        try (CloseableHttpResponse response = httpClient.execute(request)) {
            int statusCode = response.getStatusLine().getStatusCode();
            assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode);
            assertEquals("Unexpected content of HTTP response.", "", EntityUtils.toString(response.getEntity()));
        }
    }
}
Also used : BasicScheme(org.apache.http.impl.auth.BasicScheme) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpGet(org.apache.http.client.methods.HttpGet) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) URI(java.net.URI) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) Test(org.junit.Test)

Aggregations

CredentialsProvider (org.apache.http.client.CredentialsProvider)271 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)223 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)201 AuthScope (org.apache.http.auth.AuthScope)138 HttpHost (org.apache.http.HttpHost)104 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)73 HttpGet (org.apache.http.client.methods.HttpGet)62 BasicScheme (org.apache.http.impl.auth.BasicScheme)49 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)48 HttpResponse (org.apache.http.HttpResponse)45 Test (org.junit.Test)44 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)41 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)40 IOException (java.io.IOException)39 URI (java.net.URI)36 Credentials (org.apache.http.auth.Credentials)36 AuthCache (org.apache.http.client.AuthCache)33 BasicAuthCache (org.apache.http.impl.client.BasicAuthCache)33 HttpClient (org.apache.http.client.HttpClient)31 RequestConfig (org.apache.http.client.config.RequestConfig)29