Setup:
I am using Spring-MVC in one of my project. I have to access a URL for which I have to use self-signed certificates. I am using the following code in my service to do that and it is all working fine.
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
}};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (GeneralSecurityException e) {
LOGGER.error(e);
}
Problem:
Since this code is in my service, it is being executed each time a new request is made via this service. Is there a way to make this code execute only once instead of for each request? Some sample with actual code will be really appreciated.
Please comment if any more explanation is required.
You can, for example, put this code into init method of separate Spring bean, it will be executed during startup of your application:
Alternatively, you can put it into
ServletContextListener.contextInitialized()to achieve the same effect.See also: