Web Server Session Token
As with other Web services, the vSphere Web service maintains session state for each client connection by using a token in the HTTP header to identify the session. The vSphere server returns a session token to the client in its response to the client connection request. Subsequent messages between client and server automatically include the token.
Each of the stand-alone samples in the SDK\vsphere-ws\java\JAX-WS\samples\com\vmware\ uses the JAX-WS TrustAllTrustCertificates class, as discussed in Example: Obtaining a Session Token - Code Fragments from VMPromoteDisks.java to ignore certificates, obtain a session token, and then connect to the server.
Caution We do not recommend that you trust all certificates in a production environment. Instead, you can look at the sample code to see how the JAX-WS libraries are used when making the connection, but set up an SSL policy that allows connection only with trusted certificates.
The logic for getting a cookie and putting it in the header looks like this:
//cookie logic
List cookies = (List) headers.get("Set-cookie");
cookieValue = (String) cookies.get(0);
StringTokenizer tokenizer = new StringTokenizer(cookieValue, ";");
cookieValue = tokenizer.nextToken();
String path = "$" + tokenizer.nextToken();
String cookie = "$Version=\"1\"; " + cookieValue + "; " + path;
 
// set the cookie in the new request header
Map map = new HashMap();
map.put("Cookie", Collections.singletonList(cookie));
 
((BindingProvider) vimPort).getRequestContext().put(
MessageContext.HTTP_REQUEST_HEADERS, map);
Accessing the HTTP Endpoint with JAX-WS
The steps for accessing any HTTP endpoint with JAX-WS bindings are listed at the beginning of Example: Obtaining a Session Token - Code Fragments from VMPromoteDisks.java. These steps include the vSphere Web Services SDK Server URL, vSphere server object, and variables.
1
In this example we use a TrustManager class to accept all certificates. This is not appropriate for a production environment. Production code should implement certificate support.
private static class TrustAllTrustManager implements javax.net.ssl.TrustManager,
javax.net.ssl.X509TrustManager {
 
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
 
public boolean isServerTrusted(
java.security.cert.X509Certificate[] certs) {
return true;
}
 
public boolean isClientTrusted(
java.security.cert.X509Certificate[] certs) {
return true;
}
 
public void checkServerTrusted(java.security.cert.X509Certificate[] certs,
String authType)
throws java.security.cert.CertificateException {
return;
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs,
String authType)
throws java.security.cert.CertificateException {
return;
}
}
 
2
public static void main(String[] args) {
try {
String serverName = args[0];
String userName = args[1];
String password = args[2];
String url = "https://"+serverName+"/sdk/vimService";
3
ManagedObjectReference for the ServiceInstance.
VimService object for access to the Web service.
VimPortType object for access to all of the methods defined in the vSphere API.
ServiceContent for access to the managed object services on the server.
The following Java code fragment shows these variable declarations:
ManagedObjectReference SVC_INST_REF
VimService vimService;
VimPortType vimPort;
ServiceContent serviceContent;
4
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
return true;
}
};
5
// Create the trust manager.
javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
javax.net.ssl.TrustManager tm = new TrustAllTrustManager();
trustAllCerts[0] = tm;
6
javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
7
javax.net.ssl.SSLSessionContext sslsc = sc.getServerSessionContext();
8
sslsc.setSessionTimeout(0);
sc.init(null, trustAllCerts, null);
9
javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
10
HttpsURLConnection.setDefaultHostnameVerifier(hv);
Accessing the vSphere Server
The steps that use the vSphere Web Services APIs to create the connection are:
1
Create a managed object reference for the ServiceInstance object on the server.
ManagedObjectReference SVC_INST_REF = new ManagedObjectReference();
SVC_INST_REF.setType("ServiceInstance");
SVC_INST_REF.setValue("ServiceInstance");
2
Create a VimService object to obtain a VimPort binding provider. The BindingProvider object provides access to the protocol fields in request/response messages. Retrieve the request context which will be used for processing message requests.
The VimServiceLocator and VimPortType objects provide access to vSphere servers. The getVimPort method returns a VimPortType object that provides access to the vSphere API methods.
vimService = new VimService();
vimPort = vimService.getVimPort();
Map<String, Object> ctxt = ((BindingProvider) vimPort).getRequestContext();
3
Store the Server URL in the request context and specify true to maintain the connection between the client and server. The client API will include the Server's HTTP cookie in its requests to maintain the session. If you do not set this to true, the Server will start a new session with each request.
ctxt.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url);
ctxt.put(BindingProvider.SESSION_MAINTAIN_PROPERTY, true);
4
Retrieve the ServiceInstance content (the ServiceContent data object) and log in to the server.
serviceContent = vimPort.retrieveServiceContent(SVC_INST_REF);
vimPort.login(serviceContent.getSessionManager(),
userName,
password,
null);
isConnected = true;
Closing the Connection
Use the VimPort object again to close the connection. Always close your server connections to maintain security.
vimPort.logout(serviceContent.getSessionManager());
} catch (Exception e) {
System.out.println(" Connect Failed ");
e.printStackTrace();
}
}//end main()
}// end class TestClient
Using the Java Samples as Reference
The following code fragment from the SDK\vsphere-ws\java\JAX-WS\samples\com\vmware\vm\
VMPromoteDisks.java sample shows another implementation of the server connection. Review the stand-alone Java samples that are shipped with your vSphere Web Services SDK, and use similar code to get a session token for your client application.
Example: Obtaining a Session Token - Code Fragments from VMPromoteDisks.java
.
.
.
private static String cookieValue = "";
private static Map headers = new HashMap();
.
.
.
private static void trustAllHttpsCertificates()
throws Exception {
 
javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
javax.net.ssl.TrustManager tm = new TrustAllTrustManager();
trustAllCerts[0] = tm;
javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
javax.net.ssl.SSLSessionContext sslsc = sc.getServerSessionContext();
sslsc.setSessionTimeout(0);
sc.init(null, trustAllCerts, null);
javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
...
private static void connect()
throws Exception {
 
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
return true;
}
};
trustAllHttpsCertificates();
HttpsURLConnection.setDefaultHostnameVerifier(hv);
 
SVC_INST_REF.setType(SVC_INST_NAME);
SVC_INST_REF.setValue(SVC_INST_NAME);
 
vimService = new VimService();
vimPort = vimService.getVimPort();
Map<String, Object> ctxt =
((BindingProvider) vimPort).getRequestContext();
 
ctxt.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url);
ctxt.put(BindingProvider.SESSION_MAINTAIN_PROPERTY, true);
 
serviceContent = vimPort.retrieveServiceContent(SVC_INST_REF);
headers =
(Map) ((BindingProvider) vimPort).getResponseContext().get(
MessageContext.HTTP_RESPONSE_HEADERS);
vimPort.login(serviceContent.getSessionManager(),
userName,
password, null);
isConnected = true;
 
propCollectorRef = serviceContent.getPropertyCollector();
rootRef = serviceContent.getRootFolder();
}
...