Skip to content

Instantly share code, notes, and snippets.

@dariahervieux
Created December 22, 2020 09:05
Show Gist options
  • Save dariahervieux/502b4a411ead95f880256abe9f23f154 to your computer and use it in GitHub Desktop.
Save dariahervieux/502b4a411ead95f880256abe9f23f154 to your computer and use it in GitHub Desktop.
Java - Spring - SSL configuration: proxy, custom trust store
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StringUtils;
import javax.annotation.PostConstruct;
import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
@Configuration
@Slf4j
public class SslConfiguration {
@Autowired
private ProxyConfiguration proxyConfiguration;
@PostConstruct
private void configureSSL() {
if (log.isDebugEnabled()) {
System.setProperty("ssl.debug", "true");
System.setProperty("javax.net.debug", "ssl");
}
String truststoreLocation = trustStorePath();
if (!StringUtils.isEmpty(truststoreLocation)) {
System.setProperty("javax.net.ssl.trustStore", truststoreLocation);
System.setProperty("javax.net.ssl.trustStoreType", "JKS");
}
String proxyUrl = proxyConfiguration.getUrl();
String proxyPort = String.valueOf(proxyConfiguration.getPort());
if (!StringUtils.isEmpty(proxyUrl)) {
System.setProperty("http.proxyHost", proxyUrl);
System.setProperty("http.proxyPort", proxyPort);
System.setProperty("https.proxyHost", proxyUrl);
System.setProperty("https.proxyPort", proxyPort);
String login = proxyConfiguration.getLogin();
if(!StringUtils.isEmpty(login)) {
String password = proxyConfiguration.getPassword();
System.setProperty("http.proxyUser", login);
System.setProperty("http.proxyPassword", password);
System.setProperty("https.proxyUser", login);
System.setProperty("https.proxyPassword", password);
}
}
}
/**
* 'custom-cacerts' is a copy of the JDK cacerts (jdk<version>\jre\lib\security) with a custom SSL certificate (self-sifned).
*/
public String trustStorePath() {
ClassPathResource classPathResource = new ClassPathResource("cacerts/custom-cacerts");
/** Creer une copie dans le répértoire temporaire*/
try {
File copy = File.createTempFile("cacert", ".jks");
try (InputStream inputStream = classPathResource.getInputStream()) {
Files.copy(inputStream, copy.toPath(),
java.nio.file.StandardCopyOption.REPLACE_EXISTING);
}
return copy.getAbsolutePath();
} catch (Exception e) {
log.error("Copy failed {}", e.getMessage());
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment