Search in sources :

Example 76 with BasicScheme

use of org.apache.http.impl.auth.BasicScheme in project wildfly by wildfly.

the class ConstraintDrivenAuthModeTestCase method testSecuredResourceWithInvalidCredential.

@Test
public void testSecuredResourceWithInvalidCredential() throws Exception {
    HttpGet request = new HttpGet(new URI(url.toExternalForm() + "secure.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_UNAUTHORIZED, statusCode);
        }
    }
}
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 77 with BasicScheme

use of org.apache.http.impl.auth.BasicScheme in project vcell by virtualcell.

the class VCellApiClient method authenticate.

public AccessTokenRepresentation authenticate(String userid, String password, boolean alreadyDigested) throws ClientProtocolException, IOException {
    // hash the password
    String digestedPassword = (alreadyDigested) ? (password) : createdDigestPassword(password);
    HttpGet httpget = new HttpGet("https://" + httpHost.getHostName() + ":" + httpHost.getPort() + "/access_token?user_id=" + userid + "&user_password=" + digestedPassword + "&client_id=" + clientID);
    if (lg.isInfoEnabled()) {
        lg.info("Executing request to retrieve access_token " + httpget.getRequestLine());
    }
    String responseBody = httpclient.execute(httpget, new VCellStringResponseHandler("authenticate()", httpget));
    String accessTokenJson = responseBody;
    if (lg.isInfoEnabled()) {
        lg.info("returned: " + accessTokenJson);
    }
    Gson gson = new Gson();
    AccessTokenRepresentation accessTokenRep = gson.fromJson(accessTokenJson, AccessTokenRepresentation.class);
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(httpHost.getHostName(), httpHost.getPort()), new UsernamePasswordCredentials("access_token", accessTokenRep.getToken()));
    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(httpHost, basicAuth);
    // Add AuthCache to the execution context
    httpClientContext = HttpClientContext.create();
    httpClientContext.setCredentialsProvider(credsProvider);
    httpClientContext.setAuthCache(authCache);
    return accessTokenRep;
}
Also used : BasicScheme(org.apache.http.impl.auth.BasicScheme) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpGet(org.apache.http.client.methods.HttpGet) AuthScope(org.apache.http.auth.AuthScope) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) Gson(com.google.gson.Gson) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) AccessTokenRepresentation(org.vcell.api.common.AccessTokenRepresentation) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 78 with BasicScheme

use of org.apache.http.impl.auth.BasicScheme in project qpid-broker-j by apache.

the class QpidRestAPIQueueCreator method getHttpClientContext.

private HttpClientContext getHttpClientContext(final HttpHost management) {
    final BasicAuthCache authCache = new BasicAuthCache();
    authCache.put(management, new BasicScheme());
    HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);
    return localContext;
}
Also used : BasicScheme(org.apache.http.impl.auth.BasicScheme) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache)

Example 79 with BasicScheme

use of org.apache.http.impl.auth.BasicScheme in project pentaho-kettle by pentaho.

the class JobEntryHTTP method getResultFromHttpSchema.

private InputStream getResultFromHttpSchema(String realUploadFile, URI uri) throws IOException, KettleException {
    HttpClient client = null;
    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    if (!Utils.isEmpty(username)) {
        String realPassword = Encr.decryptPasswordOptionallyEncrypted(environmentSubstitute(password));
        String realUser = environmentSubstitute(username);
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(realUser, realPassword != null ? realPassword : "");
        CredentialsProvider provider = new BasicCredentialsProvider();
        provider.setCredentials(AuthScope.ANY, credentials);
        clientBuilder.setDefaultCredentialsProvider(provider);
    }
    String proxyHostnameValue = environmentSubstitute(proxyHostname);
    String proxyPortValue = environmentSubstitute(proxyPort);
    String nonProxyHostsValue = environmentSubstitute(nonProxyHosts);
    if (!Utils.isEmpty(proxyHostnameValue)) {
        HttpHost proxy = new HttpHost(proxyHostnameValue, Integer.parseInt(proxyPortValue));
        clientBuilder.setProxy(proxy);
        if (!Utils.isEmpty(nonProxyHostsValue)) {
            HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy) {

                @Override
                public HttpRoute determineRoute(final HttpHost host, final HttpRequest request, final HttpContext context) throws HttpException {
                    String hostName = host.getHostName();
                    if (hostName.matches(nonProxyHostsValue)) {
                        // Return direct route
                        return new HttpRoute(host);
                    }
                    return super.determineRoute(host, request, context);
                }
            };
            clientBuilder.setRoutePlanner(routePlanner);
        }
    }
    client = clientBuilder.build();
    HttpRequestBase httpRequestBase;
    // See if we need to send a file over?
    if (!Utils.isEmpty(realUploadFile)) {
        if (log.isDetailed()) {
            logDetailed(BaseMessages.getString(PKG, "JobHTTP.Log.SendingFile", realUploadFile));
        }
        httpRequestBase = new HttpPost(uri);
        // Get content of file
        String content = new String(Files.readAllBytes(Paths.get(realUploadFile)));
        // upload data to web server
        StringEntity requestEntity = new StringEntity(content);
        requestEntity.setContentType("application/x-www-form-urlencoded");
        ((HttpPost) httpRequestBase).setEntity(requestEntity);
        if (log.isDetailed()) {
            logDetailed(BaseMessages.getString(PKG, "JobHTTP.Log.FinishedSendingFile"));
        }
    } else {
        httpRequestBase = new HttpGet(uri);
    }
    // if we have HTTP headers, add them
    if (!Utils.isEmpty(headerName)) {
        if (log.isDebug()) {
            log.logDebug(BaseMessages.getString(PKG, "JobHTTP.Log.HeadersProvided"));
        }
        for (int j = 0; j < headerName.length; j++) {
            if (!Utils.isEmpty(headerValue[j])) {
                httpRequestBase.addHeader(environmentSubstitute(headerName[j]), environmentSubstitute(headerValue[j]));
                if (log.isDebug()) {
                    log.logDebug(BaseMessages.getString(PKG, "JobHTTP.Log.HeaderSet", environmentSubstitute(headerName[j]), environmentSubstitute(headerValue[j])));
                }
            }
        }
    }
    // Get a stream for the specified URL
    HttpResponse response = null;
    if (!Utils.isEmpty(proxyHostname)) {
        HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local
        // auth cache
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(target, basicAuth);
        // Add AuthCache to the execution context
        HttpClientContext localContext = HttpClientContext.create();
        localContext.setAuthCache(authCache);
        response = client.execute(target, httpRequestBase, localContext);
    } else {
        response = client.execute(httpRequestBase);
    }
    responseStatusCode = response.getStatusLine().getStatusCode();
    if (HttpStatus.SC_OK != responseStatusCode) {
        throw new KettleException("StatusCode: " + responseStatusCode);
    }
    if (log.isDetailed()) {
        logDetailed(BaseMessages.getString(PKG, "JobHTTP.Log.StartReadingReply"));
    }
    logBasic(BaseMessages.getString(PKG, "JobHTTP.Log.ReplayInfo", response.getEntity().getContentType(), response.getLastHeader(HttpHeaders.DATE).getValue()));
    // Read the result from the server...
    return response.getEntity().getContent();
}
Also used : HttpRequest(org.apache.http.HttpRequest) HttpPost(org.apache.http.client.methods.HttpPost) BasicScheme(org.apache.http.impl.auth.BasicScheme) KettleException(org.pentaho.di.core.exception.KettleException) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HttpGet(org.apache.http.client.methods.HttpGet) HttpContext(org.apache.http.protocol.HttpContext) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) DefaultProxyRoutePlanner(org.apache.http.impl.conn.DefaultProxyRoutePlanner) HttpResponse(org.apache.http.HttpResponse) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) ValueMetaString(org.pentaho.di.core.row.value.ValueMetaString) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) HttpRoute(org.apache.http.conn.routing.HttpRoute) StringEntity(org.apache.http.entity.StringEntity) HttpHost(org.apache.http.HttpHost) HttpRoutePlanner(org.apache.http.conn.routing.HttpRoutePlanner) HttpClient(org.apache.http.client.HttpClient)

Example 80 with BasicScheme

use of org.apache.http.impl.auth.BasicScheme in project pentaho-kettle by pentaho.

the class HTTP method callHttpService.

@VisibleForTesting
Object[] callHttpService(RowMetaInterface rowMeta, Object[] rowData) throws KettleException {
    HttpClientManager.HttpClientBuilderFacade clientBuilder = HttpClientManager.getInstance().createBuilder();
    if (data.realConnectionTimeout > -1) {
        clientBuilder.setConnectionTimeout(data.realConnectionTimeout);
    }
    if (data.realSocketTimeout > -1) {
        clientBuilder.setSocketTimeout(data.realSocketTimeout);
    }
    if (StringUtils.isNotBlank(data.realHttpLogin)) {
        clientBuilder.setCredentials(data.realHttpLogin, data.realHttpPassword);
    }
    if (StringUtils.isNotBlank(data.realProxyHost)) {
        clientBuilder.setProxy(data.realProxyHost, data.realProxyPort);
    }
    CloseableHttpClient httpClient = clientBuilder.build();
    // Prepare HTTP get
    URI uri = null;
    try {
        URIBuilder uriBuilder = constructUrlBuilder(rowMeta, rowData);
        uri = uriBuilder.build();
        HttpGet method = new HttpGet(uri);
        // Add Custom HTTP headers
        if (data.useHeaderParameters) {
            for (int i = 0; i < data.header_parameters_nrs.length; i++) {
                method.addHeader(data.headerParameters[i].getName(), data.inputRowMeta.getString(rowData, data.header_parameters_nrs[i]));
                if (isDebug()) {
                    log.logDebug(BaseMessages.getString(PKG, "HTTPDialog.Log.HeaderValue", data.headerParameters[i].getName(), data.inputRowMeta.getString(rowData, data.header_parameters_nrs[i])));
                }
            }
        }
        Object[] newRow = null;
        if (rowData != null) {
            newRow = rowData.clone();
        }
        // Execute request
        CloseableHttpResponse httpResponse = null;
        try {
            // used for calculating the responseTime
            long startTime = System.currentTimeMillis();
            HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
            // Create AuthCache instance
            AuthCache authCache = new BasicAuthCache();
            // Generate BASIC scheme object and add it to the local
            // auth cache
            BasicScheme basicAuth = new BasicScheme();
            authCache.put(target, basicAuth);
            // Add AuthCache to the execution context
            HttpClientContext localContext = HttpClientContext.create();
            localContext.setAuthCache(authCache);
            // Preemptive authentication
            if (StringUtils.isNotBlank(data.realProxyHost)) {
                httpResponse = httpClient.execute(target, method, localContext);
            } else {
                httpResponse = httpClient.execute(method, localContext);
            }
            // calculate the responseTime
            long responseTime = System.currentTimeMillis() - startTime;
            if (log.isDetailed()) {
                log.logDetailed(BaseMessages.getString(PKG, "HTTP.Log.ResponseTime", responseTime, uri));
            }
            int statusCode = requestStatusCode(httpResponse);
            // The status code
            if (isDebug()) {
                logDebug(BaseMessages.getString(PKG, "HTTP.Log.ResponseStatusCode", "" + statusCode));
            }
            String body;
            switch(statusCode) {
                case HttpURLConnection.HTTP_UNAUTHORIZED:
                    throw new KettleStepException(BaseMessages.getString(PKG, "HTTP.Exception.Authentication", data.realUrl));
                case -1:
                    throw new KettleStepException(BaseMessages.getString(PKG, "HTTP.Exception.IllegalStatusCode", data.realUrl));
                case HttpURLConnection.HTTP_NO_CONTENT:
                    body = "";
                    break;
                default:
                    HttpEntity entity = httpResponse.getEntity();
                    if (entity != null) {
                        body = StringUtils.isEmpty(meta.getEncoding()) ? EntityUtils.toString(entity) : EntityUtils.toString(entity, meta.getEncoding());
                    } else {
                        body = "";
                    }
                    break;
            }
            Header[] headers = searchForHeaders(httpResponse);
            JSONObject json = new JSONObject();
            for (Header header : headers) {
                Object previousValue = json.get(header.getName());
                if (previousValue == null) {
                    json.put(header.getName(), header.getValue());
                } else if (previousValue instanceof List) {
                    List<String> list = (List<String>) previousValue;
                    list.add(header.getValue());
                } else {
                    ArrayList<String> list = new ArrayList<String>();
                    list.add((String) previousValue);
                    list.add(header.getValue());
                    json.put(header.getName(), list);
                }
            }
            String headerString = json.toJSONString();
            int returnFieldsOffset = rowMeta.size();
            if (!Utils.isEmpty(meta.getFieldName())) {
                newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, body);
                returnFieldsOffset++;
            }
            if (!Utils.isEmpty(meta.getResultCodeFieldName())) {
                newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, new Long(statusCode));
                returnFieldsOffset++;
            }
            if (!Utils.isEmpty(meta.getResponseTimeFieldName())) {
                newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, new Long(responseTime));
                returnFieldsOffset++;
            }
            if (!Utils.isEmpty(meta.getResponseHeaderFieldName())) {
                newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, headerString);
            }
        } finally {
            if (httpResponse != null) {
                httpResponse.close();
            }
            // Release current connection to the connection pool once you are done
            method.releaseConnection();
        }
        return newRow;
    } catch (UnknownHostException uhe) {
        throw new KettleException(BaseMessages.getString(PKG, "HTTP.Error.UnknownHostException", uhe.getMessage()));
    } catch (Exception e) {
        throw new KettleException(BaseMessages.getString(PKG, "HTTP.Log.UnableGetResult", uri), e);
    }
}
Also used : KettleException(org.pentaho.di.core.exception.KettleException) KettleStepException(org.pentaho.di.core.exception.KettleStepException) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) ArrayList(java.util.ArrayList) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) URI(java.net.URI) HttpClientManager(org.pentaho.di.core.util.HttpClientManager) HttpHost(org.apache.http.HttpHost) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) ArrayList(java.util.ArrayList) List(java.util.List) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) BasicScheme(org.apache.http.impl.auth.BasicScheme) UnknownHostException(java.net.UnknownHostException) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) KettleException(org.pentaho.di.core.exception.KettleException) UnknownHostException(java.net.UnknownHostException) KettleValueException(org.pentaho.di.core.exception.KettleValueException) KettleStepException(org.pentaho.di.core.exception.KettleStepException) URIBuilder(org.apache.http.client.utils.URIBuilder) Header(org.apache.http.Header) JSONObject(org.json.simple.JSONObject) JSONObject(org.json.simple.JSONObject) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Aggregations

BasicScheme (org.apache.http.impl.auth.BasicScheme)82 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)57 CredentialsProvider (org.apache.http.client.CredentialsProvider)48 BasicAuthCache (org.apache.http.impl.client.BasicAuthCache)47 AuthCache (org.apache.http.client.AuthCache)46 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)46 HttpHost (org.apache.http.HttpHost)45 AuthScope (org.apache.http.auth.AuthScope)38 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)32 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)25 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)24 HttpGet (org.apache.http.client.methods.HttpGet)23 URI (java.net.URI)20 Test (org.junit.Test)18 IOException (java.io.IOException)13 Credentials (org.apache.http.auth.Credentials)13 HttpResponse (org.apache.http.HttpResponse)9 HttpPost (org.apache.http.client.methods.HttpPost)9 BasicHttpContext (org.apache.http.protocol.BasicHttpContext)9 Header (org.apache.http.Header)8