Как избежать проверки сертификата в spring-boot-admin? - PullRequest
0 голосов
/ 13 мая 2018

Как можно избежать проверки сертификата в spring-boot-admin?

Изображение ошибки ссылки: https://ibb.co/fkZu8y

Я настраиваю RestTemplate, чтобы избежать сертификата в классе, но я не знаю, как его отправить, я думаю, он должен быть в клиенте, spring-boot-admin-starter-client работает автоматически.

Это код, позволяющий избежать проверки сертификата.

public class SSLUtil {

    public RestTemplate getRestTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
        TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                return true;
            }
        };
        SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy)
                .build();
        SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        return restTemplate;
    }

}

Application.properties

spring.application.name = Admin-приложения

server.port = 1111

security.user.name = админ

security.user.password = admin123

@Configuration
    public static class SecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            // Page with login form is served as /login.html and does a POST on
            // /login
            http.formLogin().loginPage("/login.html").loginProcessingUrl("/login").permitAll();
            // The UI does a POST on /logout on logout
            http.logout().logoutUrl("/logout");
            // The ui currently doesn't support csrf
            http.csrf().disable().authorizeRequests()

                    // Requests for the login page and the static assets are
                    // allowed
                    // http.authorizeRequests()
                    .antMatchers("/login.html", "/**/*.css", "/img/**", "/third-party/**").permitAll();
            // ... and any other request needs to be authorized
            http.authorizeRequests().antMatchers("/**").authenticated();

            // Enable so that the clients can authenticate via HTTP basic for
            // registering
            http.httpBasic();
        }
    }

Ответы [ 2 ]

0 голосов
/ 20 марта 2019

Я использую Spring Boot Admin 2.1.3 вместе с Eureka.

Кажется, SBA перешел с RestTemplate на WebClient.Поэтому я создаю WebClient с SSLContext с диспетчером доверия, установленным на InsecureTrustManagerFactory, который доверяет всему.Затем я использую этот веб-клиент и создаю экземпляр SBA InstanceWebClient.Не уверен, что есть более простой подход, но у меня это сработало.

import de.codecentric.boot.admin.server.config.AdminServerProperties;
import de.codecentric.boot.admin.server.web.client.HttpHeadersProvider;
import de.codecentric.boot.admin.server.web.client.InstanceExchangeFilterFunction;
import de.codecentric.boot.admin.server.web.client.InstanceWebClient;
import io.netty.channel.ChannelOption;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import io.netty.handler.timeout.ReadTimeoutHandler;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.netty.ConnectionObserver;
import reactor.netty.http.client.HttpClient;

import javax.net.ssl.SSLException;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Configuration
@EnableConfigurationProperties(AdminServerProperties.class)
public class SslConfiguration {

    private final AdminServerProperties adminServerProperties;

    public SslConfiguration(AdminServerProperties adminServerProperties) {
        this.adminServerProperties = adminServerProperties;
    }


    @Bean
    public InstanceWebClient instanceWebClient(HttpHeadersProvider httpHeadersProvider,
                                        ObjectProvider<List<InstanceExchangeFilterFunction>> filtersProvider) throws SSLException {
        List<InstanceExchangeFilterFunction> additionalFilters = filtersProvider.getIfAvailable(Collections::emptyList);
        return InstanceWebClient.builder()
                .defaultRetries(adminServerProperties.getMonitor().getDefaultRetries())
                .retries(adminServerProperties.getMonitor().getRetries())
                .httpHeadersProvider(httpHeadersProvider)
                .webClient(getWebClient())
                .filters(filters -> filters.addAll(additionalFilters))
                .build();
    }

    private WebClient getWebClient() throws SSLException {
        SslContext sslContext = SslContextBuilder
                .forClient()
                .trustManager(InsecureTrustManagerFactory.INSTANCE)
                .build();

        HttpClient httpClient = HttpClient.create()
                .compress(true)
                .secure(t -> t.sslContext(sslContext))
                .tcpConfiguration(tcp -> tcp.bootstrap(bootstrap -> bootstrap.option(
                        ChannelOption.CONNECT_TIMEOUT_MILLIS,
                        (int) adminServerProperties.getMonitor().getConnectTimeout().toMillis()
                )).observe((connection, newState) -> {
                    if (ConnectionObserver.State.CONNECTED.equals(newState)) {
                        connection.addHandlerLast(new ReadTimeoutHandler(adminServerProperties.getMonitor().getReadTimeout().toMillis(),
                                TimeUnit.MILLISECONDS
                        ));
                    }
                }));
        ReactorClientHttpConnector reactorClientHttpConnector = new ReactorClientHttpConnector(httpClient);

        return WebClient.builder().clientConnector(reactorClientHttpConnector).build();
    }
}
0 голосов
/ 14 мая 2018

Попробуйте http.csrf (). Disable (). AuthorizeRequests (). Приведенный выше код отключит токен csrf.Ниже мой код для OAuth, где я отключил csrf, чтобы уменьшить сложность.

@RestController
@EnableOAuth2Sso
@EnableResourceServer
@SpringBootApplication
public class SpringBootWebApplication extends WebSecurityConfigurerAdapter {
            @Override
            protected void configure(HttpSecurity http) throws Exception {

                http.csrf().disable().authorizeRequests()

                        .antMatchers("/api/**", "/dashboard", "/welcome","/about").authenticated().antMatchers("/**").permitAll()
                        .anyRequest().authenticated().and().logout().logoutSuccessUrl("/").permitAll();

            }
...