VMware Cloud Community
nblr06
Enthusiast
Enthusiast
Jump to solution

obtain vcenter server 8 API token string?

**edit notes: the vcenter server is version 8.0.1

I'm trying to use powerCLI to acquire the sesison token string from vcenter 8 but the ps script always failed.

(Note that the vcenter server 8 is in lab, not domain joined and not for production.)

The content of the script is shown below:

# VMware vCenter 8 API URL
$apiUrl = "https://<the_ip_or_hostname>/rest/com/vmware/cis/session"
# vCenter credentials
$vcUsername = "<vcenter_user_account"
$vcPassword = "<the_user_password>"

#bypass ssl/tls and certificate issue
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}

# Create a base64-encoded string for authentication
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("${vcUsername}:${vcPassword}")))
# Headers for the API request
$headers = @{
"Authorization" = "Basic $base64AuthInfo"
}
# Make the API request to obtain the session token
$response = Invoke-RestMethod -Uri $apiUrl -Method Post -Headers $headers
# Extract the session token from the response
$sessionToken = $response.value
# Display the session token
Write-Host "Session Token: $sessionToken"
Read-Host "Extraction completed, press enter to exit"

And the error messages are always the same:

Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on
a send.
At C:\script.ps1:16 char:13
+ $response = Invoke-RestMethod -Uri $apiUrl -Method Post -Headers $hea ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest
) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands
.InvokeRestMethodCommand

Does anyone encounter this situation before?Any suggestions?

0 Kudos
1 Solution

Accepted Solutions
salcinad
Enthusiast
Enthusiast
Jump to solution

try to add this on to of your script, it solves for me the trust relationship error in different case, maybe it can help you to.

 

# Problem: Get-OVIloSso : Exception calling "GetResponse" with "0" argument(s): "The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel."
add-type @"
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    public class TrustAllCertsPolicy : ICertificatePolicy {
        public bool CheckValidationResult(
            ServicePoint srvPoint, X509Certificate certificate,
            WebRequest request, int certificateProblem) {
            return true;
        }
    }
"@
 
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

 

 

View solution in original post

10 Replies
LucD
Leadership
Leadership
Jump to solution

Works for me.
Can you try adding the Verbose switch on the Invoke-RestMethod cmdlet?


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
nblr06
Enthusiast
Enthusiast
Jump to solution

Just did and the output showed one more line at the top of the error messages:

VERBOSE: POST https://<myvcenteripaddress>/rest/com/vmware/cis/session with 0-byte payload

this is weird...

I can browse the vcenter web client using browser without problem but powershell cmdlet seemed not working on connecting URL.

0 Kudos
LucD
Leadership
Leadership
Jump to solution

You only selected TLS 1.2, can you also select TLS 1.0 and 1.1 (just to check it is not a TLS issue)?


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
nblr06
Enthusiast
Enthusiast
Jump to solution

Terribly sorry for the mistake, my vcenter server is version 8.0.1 not 7.

However, after changing the securityprotocol command to [System.Net.ServicePointManager]::SecurityProtocol = "tls12,tls11,tls" and verify that the operating system has tls 1.0~1.2 enabled(as a client), the script still failed to connect and the messages were still the same:

VERBOSE: POST https://<myvcenteripaddress>/rest/com/vmware/cis/session  with 0-byte payload
Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a send.

looks like the issue is just about connection?

0 Kudos
LucD
Leadership
Leadership
Jump to solution

I also tested against VCSA 8.*, it works for me.

Btw, did you also try the method from the PowerCLI Client SDK Example on the Create Session page?

Did you also try if Connect-CisServer works?



Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
LucD
Leadership
Leadership
Jump to solution

I noticed there is an error in the example, the Server parameter seems to be missing on the Invoke-CreateSession cmdlet.
This works for me

# Create vSphere Server Configuration with the provided Credentials.
$serverConfiguration = New-vSphereServerConfiguration -Server $Server -User $User -Password $Password
# Creates a Session with the vSphere API.
$apiSession = Invoke-CreateSession -Server $serverConfiguration -WithHttpInfo
# Set the API Key in the vSphere Server Configuration, received with the API Session.
$serverConfiguration = $serverConfiguration | Set-vSphereServerConfigurationApiKey -SessionResponse $apiSession

The result is in $apiSession.Response.



Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
nblr06
Enthusiast
Enthusiast
Jump to solution

Unfortunately, it didn't work either.

the error messages are basically the same but a little bit different:

Invoke-ApiClient : The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
At
C:\Users\test\Documents\WindowsPowerShell\Modules\VMware.Sdk.vSphereRuntime\8.0.1669.22649494\Private\vSphereApiClient.ps1:128
char:9

I also tried deploying a new vcenter server 8 and connecting to it using the methods that we've discussed. Still in vain.

Hope it's not due to some configurations in the vcenter that need to be set beforehand, I just didn't find them.

0 Kudos
salcinad
Enthusiast
Enthusiast
Jump to solution

try to add this on to of your script, it solves for me the trust relationship error in different case, maybe it can help you to.

 

# Problem: Get-OVIloSso : Exception calling "GetResponse" with "0" argument(s): "The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel."
add-type @"
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    public class TrustAllCertsPolicy : ICertificatePolicy {
        public bool CheckValidationResult(
            ServicePoint srvPoint, X509Certificate certificate,
            WebRequest request, int certificateProblem) {
            return true;
        }
    }
"@
 
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

 

 

LucD
Leadership
Leadership
Jump to solution

Are you using PSv5.* or PSv7.*?
If you are using PSv7.* you can try adding the SkipCertificateCheck switch on the Invoke-WebRequest cmdlet.

If you are using PSv5.* that switch is not available, but you can use something like this (code from rest - Invoke-RestMethod - Ignore Self Signed Certs - Stack Overflow)

if (-not("dummy" -as [type])) {
    add-type -TypeDefinition @"
using System;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

public static class Dummy {
    public static bool ReturnTrue(object sender,
        X509Certificate certificate,
        X509Chain chain,
        SslPolicyErrors sslPolicyErrors) { return true; }

    public static RemoteCertificateValidationCallback GetDelegate() {
        return new RemoteCertificateValidationCallback(Dummy.ReturnTrue);
    }
}
"@
}

[System.Net.ServicePointManager]::ServerCertificateValidationCallback = [dummy]::GetDelegate()

 


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
nblr06
Enthusiast
Enthusiast
Jump to solution

This solved the issue! Both my script and the code examples from https://developer.vmware.com/apis/vsphere-automation/latest/cis/api/session/post/ can obtain the vcenter session token.

The ssl/tls connection issue is too troublesome...I prefer a simpler script but for now your codes can handle it thus currently that's the best answer for me.

Thanks!!

Regarding to @LucD's reply, I'm using powershell v5.1 to do the work.

I'll find another day to try your suggestions.

Thanks for your enthusiastic help in these days!!

0 Kudos