vCenter REST API authentication

Viewed 25523

I am following this VMware documentation. What headers are to be provided to authenticate to vCenter Server while using REST API?

6 Answers

For python:

import requests

# https://vdc-download.vmware.com/vmwb-repository/dcr-public/1cd28284-3b72-4885-9e31-d1c6d9e26686/71ef7304-a6c9-43b3-a3cd-868b2c236c81/doc/operations/com/vmware/vcenter/vm.list-operation.html

sess = requests.post("https://XXXXXXXX/rest/com/vmware/cis/session", auth=('USERNAME', 'PASSWORD'), verify=False)
session_id = sess.json()['value']

resp = requests.get("https://XXXXXXXX/rest/vcenter/vm", verify=False, headers={
    "vmware-api-session-id": session_id
})
print(u"resp.text = %s" % str(resp.text))

PowerShell:

$User="<username>"
$Pass="<password>"
$Auth=$User+":"+$Pass
$Encoded=[System.Text.Encoding]::UTF8.GetBytes($Auth)
$EncodedAuth=[System.Convert]::ToBase64String($Encoded)
$Headers = @{"Authorization"="Basic $($EncodedAuth)"}
$SecPass=ConvertTo-SecureString -String $Pass -AsPlainText -Force
$Cred=[System.Management.Automation.PSCredential]::new($User,$SecPass)

<# Uncomment this part if you don't have a valid trusted certificate
$strIDontCarePolicy=@"
using System.Net;
using System.Security.Cryptography.X509Certificates;

public class IDontCarePolicy : ICertificatePolicy {
  public IDontCarePolicy() {}
  public bool CheckValidationResult(ServicePoint sPoint, X509Certificate cert, WebRequest wRequest, int certProb) { return true; }
}
"@
Add-Type -TypeDefinition $strIDontCarePolicy -PassThru
[System.Net.ServicePointManager]::CertificatePolicy = New-Object IDontCarePolicy 
#>

$initSession=Invoke-RestMethod -Uri "https://<vCenter Server>/rest/com/vmware/cis/session" -Method Post -Headers $Headers
$SessionID=$initSession.Value

for .NET Client

//only if you dont have valid certificate ignore certificate

var handler = new HttpClientHandler();
        handler.ClientCertificateOptions = ClientCertificateOption.Manual;
        handler.ServerCertificateCustomValidationCallback =
            (httpRequestMessage, cert, cetChain, policyErrors) =>
            {
                return true;
            };


        using (var client = new HttpClient(handler))
        {
            var values = new Dictionary<string, string>
            {

            };

            client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
    "Basic", Convert.ToBase64String(
        System.Text.ASCIIEncoding.ASCII.GetBytes(
           $"{"username"}:{"password"}")));
            var content = new FormUrlEncodedContent(values);
            //var stringContent = new StringContent(content, Encoding.UTF8, "application/x-www-form-urlencoded");

            var response = await client.PostAsync("https://vcsa/rest/com/vmware/cis/session", content);

            var responseString = await response.Content.ReadAsAsync<KeyValuePair<string, string>>();
            client.DefaultRequestHeaders.Authorization
                     = new AuthenticationHeaderValue("Bearer", responseString.Value);
            var vmRespone = await client.GetAsync("https://vcsa/rest/vcenter/vm");

        }

Be aware that VMware has a now deprecated API served under /rest which is only valid up to vSphere 7.0 Update 2. Beginning from vSphere 7.0, there is a new API served under /api, which uses similar URLs to the previous API, but some differ. And also the returned JSON differs.

Python example for the old API:

import requests

# Get session ID
response = requests.post("https://<VCENTER>/rest/com/vmware/cis/session", auth=(<USER>, <PASSWORD>))
if response.ok:
    sessionId = response.json()['value']
else:
    raise ValueError("Unable to retrieve a session ID.")

# Get VMs, for example
response = requests.get("https://<VCENTER>/rest/vcenter/vm", headers={"vmware-api-session-id": session_id})
if response.ok:
    print(f"VMs: {response.json()['value']}")
else:
    raise ValueError("Unable to retrieve VMs.")

Python example for the new API:

import requests

# Get session ID
response = requests.post("https://<VCENTER>/api/session", auth=(<USER>, <PASSWORD>))
if response.ok:
    sessionId = response.json()
else:
    raise ValueError("Unable to retrieve a session ID.")

# Get VMs, for example
response = requests.get("https://<VCENTER>/api/vcenter/vm", headers={"vmware-api-session-id": session_id})
if response.ok:
    print(f"VMs: {response.json()}")
else:
    raise ValueError("Unable to retrieve VMs.")

For more info on the API change, have a look at this article.

Using username@vsphere.local in curl calls gave authentication errors.

We switched to VSPHERE.LOCAL\username which worked without issues.

Related