Search in sources :

Example 81 with BasicCredentialsProvider

use of org.apache.http.impl.client.BasicCredentialsProvider in project spring-boot-admin by codecentric.

the class AdminServerNotifierAutoConfiguration method createNotifierRestTemplate.

private static RestTemplate createNotifierRestTemplate(NotifierProxyProperties proxyProperties) {
    RestTemplate restTemplate = new RestTemplate();
    if (proxyProperties.getHost() != null) {
        HttpClientBuilder builder = HttpClientBuilder.create();
        builder.setProxy(new HttpHost(proxyProperties.getHost(), proxyProperties.getPort()));
        if (proxyProperties.getUsername() != null && proxyProperties.getPassword() != null) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(proxyProperties.getHost(), proxyProperties.getPort()), new UsernamePasswordCredentials(proxyProperties.getUsername(), proxyProperties.getPassword()));
            builder.setDefaultCredentialsProvider(credsProvider);
        }
        restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(builder.build()));
    }
    return restTemplate;
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpHost(org.apache.http.HttpHost) RestTemplate(org.springframework.web.client.RestTemplate) AuthScope(org.apache.http.auth.AuthScope) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) HttpComponentsClientHttpRequestFactory(org.springframework.http.client.HttpComponentsClientHttpRequestFactory) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 82 with BasicCredentialsProvider

use of org.apache.http.impl.client.BasicCredentialsProvider in project hbase by apache.

the class TestThriftSpnegoHttpFallbackServer method createHttpClient.

private CloseableHttpClient createHttpClient() throws Exception {
    final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(clientPrincipal, clientKeytab);
    final Set<Principal> clientPrincipals = clientSubject.getPrincipals();
    // Make sure the subject has a principal
    assertFalse("Found no client principals in the clientSubject.", clientPrincipals.isEmpty());
    // Get a TGT for the subject (might have many, different encryption types). The first should
    // be the default encryption type.
    Set<KerberosTicket> privateCredentials = clientSubject.getPrivateCredentials(KerberosTicket.class);
    assertFalse("Found no private credentials in the clientSubject.", privateCredentials.isEmpty());
    KerberosTicket tgt = privateCredentials.iterator().next();
    assertNotNull("No kerberos ticket found.", tgt);
    // The name of the principal
    final String clientPrincipalName = clientPrincipals.iterator().next().getName();
    return Subject.doAs(clientSubject, (PrivilegedExceptionAction<CloseableHttpClient>) () -> {
        // Logs in with Kerberos via GSS
        GSSManager gssManager = GSSManager.getInstance();
        // jGSS Kerberos login constant
        Oid oid = new Oid("1.2.840.113554.1.2.2");
        GSSName gssClient = gssManager.createName(clientPrincipalName, GSSName.NT_USER_NAME);
        GSSCredential credential = gssManager.createCredential(gssClient, GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.INITIATE_ONLY);
        Lookup<AuthSchemeProvider> authRegistry = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, true)).build();
        BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new KerberosCredentials(credential));
        return HttpClients.custom().setDefaultAuthSchemeRegistry(authRegistry).setDefaultCredentialsProvider(credentialsProvider).build();
    });
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) GSSName(org.ietf.jgss.GSSName) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) KerberosTicket(javax.security.auth.kerberos.KerberosTicket) KerberosCredentials(org.apache.http.auth.KerberosCredentials) Oid(org.ietf.jgss.Oid) SPNegoSchemeFactory(org.apache.http.impl.auth.SPNegoSchemeFactory) Subject(javax.security.auth.Subject) GSSCredential(org.ietf.jgss.GSSCredential) GSSManager(org.ietf.jgss.GSSManager) Lookup(org.apache.http.config.Lookup) Principal(java.security.Principal)

Example 83 with BasicCredentialsProvider

use of org.apache.http.impl.client.BasicCredentialsProvider in project hbase by apache.

the class TestInfoServersACL method createHttpClient.

private CloseableHttpClient createHttpClient(String clientPrincipal) throws Exception {
    // Logs in with Kerberos via GSS
    GSSManager gssManager = GSSManager.getInstance();
    // jGSS Kerberos login constant
    Oid oid = new Oid("1.2.840.113554.1.2.2");
    GSSName gssClient = gssManager.createName(clientPrincipal, GSSName.NT_USER_NAME);
    GSSCredential credential = gssManager.createCredential(gssClient, GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.INITIATE_ONLY);
    Lookup<AuthSchemeProvider> authRegistry = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, true)).build();
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new KerberosCredentials(credential));
    return HttpClients.custom().setDefaultAuthSchemeRegistry(authRegistry).setDefaultCredentialsProvider(credentialsProvider).build();
}
Also used : GSSName(org.ietf.jgss.GSSName) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) GSSCredential(org.ietf.jgss.GSSCredential) GSSManager(org.ietf.jgss.GSSManager) KerberosCredentials(org.apache.http.auth.KerberosCredentials) Oid(org.ietf.jgss.Oid) AuthSchemeProvider(org.apache.http.auth.AuthSchemeProvider) SPNegoSchemeFactory(org.apache.http.impl.auth.SPNegoSchemeFactory)

Example 84 with BasicCredentialsProvider

use of org.apache.http.impl.client.BasicCredentialsProvider in project hbase by apache.

the class TestThriftSpnegoHttpServer method createHttpClient.

private CloseableHttpClient createHttpClient() throws Exception {
    final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(clientPrincipal, clientKeytab);
    final Set<Principal> clientPrincipals = clientSubject.getPrincipals();
    // Make sure the subject has a principal
    assertFalse("Found no client principals in the clientSubject.", clientPrincipals.isEmpty());
    // Get a TGT for the subject (might have many, different encryption types). The first should
    // be the default encryption type.
    Set<KerberosTicket> privateCredentials = clientSubject.getPrivateCredentials(KerberosTicket.class);
    assertFalse("Found no private credentials in the clientSubject.", privateCredentials.isEmpty());
    KerberosTicket tgt = privateCredentials.iterator().next();
    assertNotNull("No kerberos ticket found.", tgt);
    // The name of the principal
    final String clientPrincipalName = clientPrincipals.iterator().next().getName();
    return Subject.doAs(clientSubject, (PrivilegedExceptionAction<CloseableHttpClient>) () -> {
        // Logs in with Kerberos via GSS
        GSSManager gssManager = GSSManager.getInstance();
        // jGSS Kerberos login constant
        Oid oid = new Oid("1.2.840.113554.1.2.2");
        GSSName gssClient = gssManager.createName(clientPrincipalName, GSSName.NT_USER_NAME);
        GSSCredential credential = gssManager.createCredential(gssClient, GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.INITIATE_ONLY);
        Lookup<AuthSchemeProvider> authRegistry = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, true)).build();
        BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new KerberosCredentials(credential));
        return HttpClients.custom().setDefaultAuthSchemeRegistry(authRegistry).setDefaultCredentialsProvider(credentialsProvider).build();
    });
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) GSSName(org.ietf.jgss.GSSName) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) KerberosTicket(javax.security.auth.kerberos.KerberosTicket) KerberosCredentials(org.apache.http.auth.KerberosCredentials) Oid(org.ietf.jgss.Oid) SPNegoSchemeFactory(org.apache.http.impl.auth.SPNegoSchemeFactory) Subject(javax.security.auth.Subject) GSSCredential(org.ietf.jgss.GSSCredential) GSSManager(org.ietf.jgss.GSSManager) Lookup(org.apache.http.config.Lookup) Principal(java.security.Principal)

Example 85 with BasicCredentialsProvider

use of org.apache.http.impl.client.BasicCredentialsProvider in project midpoint by Evolveum.

the class SmsMessageTransport method send.

@Override
public void send(Message message, String transportName, Event event, Task task, OperationResult parentResult) {
    OperationResult result = parentResult.createSubresult(DOT_CLASS + "send");
    result.addArbitraryObjectCollectionAsParam("message recipient(s)", message.getTo());
    result.addParam("message subject", message.getSubject());
    String logToFile = configuration.getLogToFile();
    if (logToFile != null) {
        TransportUtil.logToFile(logToFile, TransportUtil.formatToFileNew(message, transportName), LOGGER);
    }
    String file = configuration.getRedirectToFile();
    int optionsForFilteringRecipient = TransportUtil.optionsForFilteringRecipient(configuration);
    List<String> allowedRecipientTo = new ArrayList<>();
    List<String> forbiddenRecipientTo = new ArrayList<>();
    if (optionsForFilteringRecipient != 0) {
        TransportUtil.validateRecipient(allowedRecipientTo, forbiddenRecipientTo, message.getTo(), configuration, task, result, transportSupport.expressionFactory(), MiscSchemaUtil.getExpressionProfile(), LOGGER);
        if (file != null) {
            if (!forbiddenRecipientTo.isEmpty()) {
                message.setTo(forbiddenRecipientTo);
                writeToFile(message, file, null, emptyList(), null, result);
            }
            message.setTo(allowedRecipientTo);
        }
    } else if (file != null) {
        writeToFile(message, file, null, emptyList(), null, result);
        return;
    }
    if (configuration.getGateway().isEmpty()) {
        String msg = "SMS gateway(s) are not defined, notification to " + message.getTo() + " will not be sent.";
        LOGGER.warn(msg);
        result.recordWarning(msg);
        return;
    }
    String from;
    if (message.getFrom() != null) {
        from = message.getFrom();
    } else if (configuration.getDefaultFrom() != null) {
        from = configuration.getDefaultFrom();
    } else {
        from = "";
    }
    if (message.getTo().isEmpty()) {
        if (optionsForFilteringRecipient != 0) {
            String msg = "After recipient validation there is no recipient to send the notification to.";
            LOGGER.debug(msg);
            result.recordSuccess();
        } else {
            String msg = "There is no recipient to send the notification to.";
            LOGGER.warn(msg);
            result.recordWarning(msg);
        }
        return;
    }
    List<String> to = message.getTo();
    assert to.size() > 0;
    for (SmsGatewayConfigurationType smsGatewayConfigurationType : configuration.getGateway()) {
        OperationResult resultForGateway = result.createSubresult(DOT_CLASS + "send.forGateway");
        resultForGateway.addContext("gateway name", smsGatewayConfigurationType.getName());
        try {
            VariablesMap variables = getDefaultVariables(from, to, message);
            HttpMethodType method = defaultIfNull(smsGatewayConfigurationType.getMethod(), HttpMethodType.GET);
            ExpressionType urlExpression = defaultIfNull(smsGatewayConfigurationType.getUrlExpression(), null);
            String url = evaluateExpressionChecked(urlExpression, variables, "sms gateway request url", task, result);
            String proxyHost = smsGatewayConfigurationType.getProxyHost();
            String proxyPort = smsGatewayConfigurationType.getProxyPort();
            LOGGER.debug("Sending SMS to URL {} via proxy host {} and port {} (method {})", url, proxyHost, proxyPort, method);
            if (url == null) {
                throw new IllegalArgumentException("No URL specified");
            }
            List<String> headersList = evaluateExpressionsChecked(smsGatewayConfigurationType.getHeadersExpression(), variables, "sms gateway request headers", task, result);
            LOGGER.debug("Using request headers:\n{}", headersList);
            String encoding = defaultIfNull(smsGatewayConfigurationType.getBodyEncoding(), StandardCharsets.ISO_8859_1.name());
            String body = evaluateExpressionChecked(smsGatewayConfigurationType.getBodyExpression(), variables, "sms gateway request body", task, result);
            LOGGER.debug("Using request body text (encoding: {}):\n{}", encoding, body);
            if (smsGatewayConfigurationType.getLogToFile() != null) {
                TransportUtil.logToFile(smsGatewayConfigurationType.getLogToFile(), formatToFile(message, url, headersList, body), LOGGER);
            }
            if (smsGatewayConfigurationType.getRedirectToFile() != null) {
                writeToFile(message, smsGatewayConfigurationType.getRedirectToFile(), url, headersList, body, resultForGateway);
                result.computeStatus();
                return;
            } else {
                HttpClientBuilder builder = HttpClientBuilder.create();
                String username = smsGatewayConfigurationType.getUsername();
                ProtectedStringType password = smsGatewayConfigurationType.getPassword();
                CredentialsProvider provider = new BasicCredentialsProvider();
                if (username != null) {
                    String plainPassword = password != null ? transportSupport.protector().decryptString(password) : null;
                    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, plainPassword);
                    provider.setCredentials(AuthScope.ANY, credentials);
                    builder = builder.setDefaultCredentialsProvider(provider);
                }
                String proxyUsername = smsGatewayConfigurationType.getProxyUsername();
                ProtectedStringType proxyPassword = smsGatewayConfigurationType.getProxyPassword();
                if (StringUtils.isNotBlank(proxyHost)) {
                    HttpHost proxy;
                    if (StringUtils.isNotBlank(proxyPort) && isInteger(proxyPort)) {
                        int port = Integer.parseInt(proxyPort);
                        proxy = new HttpHost(proxyHost, port);
                    } else {
                        proxy = new HttpHost(proxyHost);
                    }
                    if (StringUtils.isNotBlank(proxyUsername)) {
                        String plainProxyPassword = proxyPassword != null ? transportSupport.protector().decryptString(proxyPassword) : null;
                        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(proxyUsername, plainProxyPassword);
                        provider.setCredentials(new AuthScope(proxy), credentials);
                    }
                    builder = builder.setDefaultCredentialsProvider(provider);
                    builder = builder.setProxy(proxy);
                }
                HttpClient client = builder.build();
                HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(client);
                ClientHttpRequest request = requestFactory.createRequest(new URI(url), HttpUtil.toHttpMethod(method));
                setHeaders(request, headersList);
                if (body != null) {
                    request.getBody().write(body.getBytes(encoding));
                }
                ClientHttpResponse response = request.execute();
                LOGGER.debug("Result: " + response.getStatusCode() + "/" + response.getStatusText());
                if (response.getStatusCode().series() != HttpStatus.Series.SUCCESSFUL) {
                    throw new SystemException("SMS gateway communication failed: " + response.getStatusCode() + ": " + response.getStatusText());
                }
                LOGGER.debug("Message sent successfully to {} via gateway {}.", message.getTo(), smsGatewayConfigurationType.getName());
                resultForGateway.recordSuccess();
                result.recordSuccess();
                return;
            }
        } catch (Throwable t) {
            String msg = "Couldn't send SMS to " + message.getTo() + " via " + smsGatewayConfigurationType.getName() + ", trying another gateway, if there is any";
            LoggingUtils.logException(LOGGER, msg, t);
            resultForGateway.recordFatalError(msg, t);
        }
    }
    LOGGER.warn("No more SMS gateways to try, notification to " + message.getTo() + " will not be sent.");
    result.recordWarning("Notification to " + message.getTo() + " could not be sent.");
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) ArrayList(java.util.ArrayList) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) ClientHttpRequest(org.springframework.http.client.ClientHttpRequest) URI(java.net.URI) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) HttpHost(org.apache.http.HttpHost) HttpClient(org.apache.http.client.HttpClient) AuthScope(org.apache.http.auth.AuthScope) VariablesMap(com.evolveum.midpoint.schema.expression.VariablesMap) HttpComponentsClientHttpRequestFactory(org.springframework.http.client.HttpComponentsClientHttpRequestFactory) ProtectedStringType(com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse)

Aggregations

BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)192 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)162 CredentialsProvider (org.apache.http.client.CredentialsProvider)147 AuthScope (org.apache.http.auth.AuthScope)104 HttpHost (org.apache.http.HttpHost)76 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)53 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)41 HttpResponse (org.apache.http.HttpResponse)38 IOException (java.io.IOException)35 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)31 HttpGet (org.apache.http.client.methods.HttpGet)30 HttpClient (org.apache.http.client.HttpClient)29 BasicAuthCache (org.apache.http.impl.client.BasicAuthCache)29 AuthCache (org.apache.http.client.AuthCache)28 BasicScheme (org.apache.http.impl.auth.BasicScheme)27 RequestConfig (org.apache.http.client.config.RequestConfig)25 HttpPost (org.apache.http.client.methods.HttpPost)20 Credentials (org.apache.http.auth.Credentials)19 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)19 Test (org.junit.Test)16