Аутентификация клиентского сертификата с помощью Spring Boot - PullRequest
0 голосов
/ 04 июля 2018

Мне нужно импортировать сертификат, чтобы сделать http-запрос к внешней службе в приложении Spring Boot.

Как мне настроить Spring Boot для этого?

Там много информации, но я нахожу это немного запутанным. Кажется, что мне просто нужно создать что-то вроде хранилища ключей "truststore.jks", импортировать правильный сертификат и добавить некоторые записи в мои application.properties.

1 Ответ

0 голосов
/ 05 июля 2018

Начните с создания самозаверяющего сертификата, используя keytool, если у вас его еще нет

Откройте свой терминал или cmd

keytool -genkeypair -alias tomcat -keyalg RSA -keysize 2048 -storetype PKCS12 -keystore keystore.p12 -validity 3650

Ответь на все вопросы. В первом вопросе: как вас зовут и фамилия поставить localhost.

Если у вас уже есть сертификат yourcertificate.crt, сделайте это

keytool -import -alias tomcat -file yourcertificate.crt -keystore keystore.p12 -storepass password

Вы получите файл с именем keystore.p12.

Скопируйте этот файл на ваш resources folder

Добавьте следующие строки в ваш properties файл

# Define a custom port instead of the default 8080
server.port=8443

# Tell Spring Security (if used) to require requests over HTTPS
security.require-ssl=true

# The format used for the keystore 
server.ssl.key-store-type=PKCS12
# The path to the keystore containing the certificate
server.ssl.key-store=classpath:keystore.p12
# The password used to generate the certificate
server.ssl.key-store-password= {your password here}
# The alias mapped to the certificate
server.ssl.key-alias=tomcat

Создайте Config класс следующим образом

@Configuration
public class ConnectorConfig {

    @Bean
    public TomcatServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
                securityConstraint.addCollection(collection);
                context.addConstraint(securityConstraint);
            }
        };
        tomcat.addAdditionalTomcatConnectors(getHttpConnector());
        return tomcat;
    }

    private Connector getHttpConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        connector.setPort(8080);
        connector.setSecure(false);
        connector.setRedirectPort(8443);
        return connector;
    }
}

Теперь ваше приложение доступно с https://localhost:8443

Теперь вы можете получить доступ к третьей службе, которая запрашивает ssl-аутентификацию

...