Java Example of Creating a
vSphere Automation
API Session with User Credentials
Last Updated December 16, 2024

This example is based on the code in the
VapiAuthenticationHelper.java
sample.
This example uses the steps that are described in the Create a vSphere Automation Session with User Credentials procedure
For a complete and up-to-date version of the Java sample code, see the
vsphere-automation-sdk-java
VMware repository at GitHub.
...

this.stubFactory = createApiStubFactory(server, httpConfig);

// Create a security context for username/password authentication
SecurityContext securityContext =
        SecurityContextFactory.createUserPassSecurityContext(
            username, password.toCharArray());

// Create a stub configuration with username/password security context
StubConfiguration stubConfig = new StubConfiguration(securityContext);

// Create a session stub using the stub configuration.
Session session =
        this.stubFactory.createStub(Session.class, stubConfig);

// Login and create a session
char[] sessionId = session.create();

// Initialize a session security context from the generated session id
SessionSecurityContext sessionSecurityContext =
        new SessionSecurityContext(sessionId);

// Update the stub configuration to use the session id
stubConfig.setSecurityContext(sessionSecurityContext);

/*
 * Create a stub for the session service using the authenticated
 * session
 */
this.sessionSvc =
        this.stubFactory.createStub(Session.class, stubConfig);

VM vmService = this.stubFactory.createStub(VM.class, stubConfig);