ONTAP Rest API Discussions

credentials with powershell

kahuna
17,515 Views

Hello all,

I want to script REST API using powershell. How do I get the credentials (token) and pass it to the commands?

something similar to this:

[the below doesn't work, but I think I am close]

$user = Read-Host “Enter username”
$pass = Read-Host -assecurestring “Enter password” | ConvertTo-SecureString -asPlainText -Force

$credential = New-Object System.Management.Automation.PSCredential($user,$pass)
$token = Invoke-WebRequest -Credential $credential -Method Post -Uri "https://192.168.0.52/XXXXXXXXXXXXXX"


Invoke-RestMethod -method GET -uri '"https://192.168.0.52/api/storage/volumes?name=vol1&fields=*&return_records=true&return_timeout=15" ' -header @{"accept" = "application/json"; "authorization" = "Basic $token"}

 

any input would be appreciated

1 ACCEPTED SOLUTION

JohnChampion
15,404 Views

It's basically telling that specific console session to trust a non-CA issued certificate (ie. self-signed).  It's a common workaround for PSv5 - give it a "google" and I'm sure you'll find a more in-depth answer than mine.

 

Also, I'm fairly certain it's actually -Headers (with an 's').  Maybe that's the issue. 🤔  

 

View solution in original post

8 REPLIES 8

JohnChampion
17,453 Views

It's "quirky" that's for sure - but I've generally handled it this way and seems to work across PowerShell versions.

 

...this example is with the ONTAP Select Deploy Utility but should work with ONTAP I would think...

Function ConvertTo-PlainText( [security.securestring]$secure ) 
{
	$marshal = [Runtime.InteropServices.Marshal] 
	$marshal::PtrToStringAuto( $marshal::SecureStringToBSTR($secure) ) 
}
Write-Host " Enter Deploy Password: " -NoNewline
$pwd = Read-Host -AsSecureString
$deploy_password = ConvertTo-PlainText $pwd
$pw = ConvertTo-SecureString -String "$deploy_password" -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "admin", $pw
$url = "https://{ip}/api/v3/clusters?name=cluster1"
Invoke-RestMethod -Method 'GET' -Uri $url -Credential $cred -SkipCertificateCheck

 

I get inconsistent behavior if I try to send the secure password directly to the New-Object call - you'd think they would be the same but perhaps not (?!?).  

 

The "-SkipCertificateCheck" switch is awesome btw - too bad it's only in PowerShell version 6/7 😁

JohnChampion
17,385 Views

After some testing I realized this actually didn't work correctly in PowerShell Core 7.0 (oops!)

 

Here's the new code (note the previous "marshal" function is not used and the change to the Read-Host cmdlet):

$pwd = Read-Host " Enter Deploy Password" -AsSecureString
$deploy_password = ConvertFrom-SecureString $pwd -AsPlainText
$pw = ConvertTo-SecureString -String "$deploy_password" -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "admin", $pw
$url = "https://{ip}/api/v3/clusters?name=cluster1"
$result = Invoke-RestMethod -Method 'GET' -Uri $url -Credential $cred -SkipCertificateCheck

 

I still couldn't pass the secure password directly (?!?)

mbeattie
17,380 Views

Hi,

 

You can pass a [System.Management.Automation.PSCredential] object to your script or function. IE prompt for credentials, then within your code use the credential object to create the header for authentication.  Here is a very basic example based on your code to query a volume on a cluster using a credential object.

 

Param(
  [Parameter(Mandatory = $True, HelpMessage = "The Cluster Name or IP Address")]
  [ValidateNotNullOrEmpty()]
  [String]$Cluster,
  [Parameter(Mandatory = $True, HelpMessage = "The Cluster Name or IP Address")]
  [ValidateNotNullOrEmpty()]
  [String]$VolumeName,
  [Parameter(Mandatory = $True, HelpMessage = "The Credential to authenticate to AIQUM")]
  [ValidateNotNullOrEmpty()]
  [System.Management.Automation.PSCredential]$Credential
)
#'------------------------------------------------------------------------------
#'Set the authentication header.
#'------------------------------------------------------------------------------
$auth    = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($Credential.UserName + ':' + $Credential.GetNetworkCredential().Password))
$headers = @{"Authorization" = "Basic $auth"}
#'------------------------------------------------------------------------------
#'Enumerate the Volume.
#'------------------------------------------------------------------------------
[String]$uri = "https://$Cluster/api/storage/volumes?name=$VolumeName&fields=*&return_records=true&return_timeout=15"
Try{
  $response = Invoke-RestMethod -method GET -uri $uri -header $headers -ErrorAction Stop
  Write-Host "Enumerated volume ""$VolumeName"" on cluster ""$Cluster"" using URI ""$uri"""
}Catch{
  Write-Warning -Message $("Failed enumerating volume ""$VolumeName"" on cluster ""$Cluster"" using URI ""$uri"". Error " + $_.Exception.Message + ". Status Code " + $_.Exception.Response.StatusCode.value__)
  Break;
}
$response.records
#'------------------------------------------------------------------------------

 

EG if you save that as "GetVolume.ps1" then prompt for a credential object using:

 

PS C:\> $credential = Get-Credential

 

Then run the script as follows (IE you can pass the cluster name, volume and credential object as input parameters to your script (or function in library). This way you can avoid having to hard code usernames or passwords in code.

 

PS C:\Scripts\PowerShell\Projects\ONTAP> .\GetVolume.ps1 -Cluster cluster2.demo.netapp.com -VolumeName volume_001 -Credential $credential
Enumerated volume "volume_001" on cluster "cluster2.demo.netapp.com" using URI "https://cluster2.demo.netapp.com/api/storage/volumes?name=volume_001&fields=*&return_records=true&return_timeout=15"


uuid            : 9838bd47-ab86-11ea-85a7-005056b01307
comment         :
create_time     : 2020-06-11T01:55:15+00:00
language        : c.utf_8
name            : volume_001
size            : 1161850880
state           : online
style           : flexvol
tiering         : @{policy=none}
type            : rw
aggregates      : {@{name=aggr1_cluster2_01; uuid=e329b91b-0633-4186-8c8d-aa4c7191da16}}
clone           : @{is_flexclone=False}
nas             : @{export_policy=}
snapshot_policy : @{name=default}
svm             : @{name=svm21; uuid=503ac2b8-acfe-11e9-8271-005056b03109; _links=}
space           : @{size=1161850880; available=21479424; used=1082281984}
snapmirror      : @{is_protected=False}
metric          : @{timestamp=2020-06-15T04:26:15Z; duration=PT15S; status=ok; latency=; iops=; throughput=}
_links          : @{self=}

 

If you don't want to be prompted for credentials you could make the credential parameter non-mandatory and checking for cached credentials using the PSTK (Get-NcCredential) so you don't have to pass the credential parameter if they have already been cached.

 

Loads of examples of using the $Credential parameter as an input into a function in the module libraries i've uploaded to github for AIQUM and VSC 

 

Hope that helps. Let me know if you have any questions

 

/Matt

 

 

 

If this post resolved your issue, help others by selecting ACCEPT AS SOLUTION or adding a KUDO.

tyrone_owen_1
15,417 Views

I'm new to PS and REST so this old post is still relevant to me. I've used a synthesis of Matt's code and combined it with how I wanted to authenticate:

 

$Cluster = "xxx.xxx.xxx.xxx"
$CredentialPath = "C:\Users\Username\Documents\PSCredentials\rest.ps1.credential"
$Credential = Import-Clixml -Path $CredentialPath
$Auth    = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($Credential.UserName + ':' + $Credential.GetNetworkCredential().Password))
$Headers = @{"Authorization" = "Basic $auth"}
[String]$Uri = "https://$Cluster/api/storage/volumes?fields=**&return_records=true&return_timeout=15"
$Response = Invoke-RestMethod -method GET -uri $Uri -header $Headers -ErrorAction Stop

However I receive the following error:

Invoke-RestMethod : The underlying connection was closed: Could not establish trust relationship for the SSL/TLS
secure channel.
At line:1 char:13
+ $Response = Invoke-RestMethod -method GET -uri $Uri -header $Headers  ...
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebExc
   eption
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

Any thoughts please? If I run the following first, running the invoke command works:

 

Connect-NcController -Name $Cluster -Credential $Credential

 

JohnChampion
15,409 Views

That error is related to the  ONTAP certificate and the Invoke-RestMethod requires a signed cert. 

 

If you're using PowerShell v7 you can add '-SkipCertificateCheck' to the end of the cmdlet and it will allow the self-signed cert from ONTAP for the https connection.

$Response = Invoke-RestMethod -method GET -uri $Uri -header $Headers -ErrorAction Stop -SkipCertificateCheck

 

If you're using PowerShell v5 it's a bit trickier.

# Allow untrusted (self signed) certificate
Add-Type @"
    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;
        }
    }
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object IDontCarePolicy

 This is only applied to the current session/console.

tyrone_owen_1
15,405 Views

Thanks John. I'm currently using PS v5.

 

Would you mind giving me a brief explainer of what is happening in the v5 resolution please? The v7 resolution, even I can understand

JohnChampion
15,405 Views

It's basically telling that specific console session to trust a non-CA issued certificate (ie. self-signed).  It's a common workaround for PSv5 - give it a "google" and I'm sure you'll find a more in-depth answer than mine.

 

Also, I'm fairly certain it's actually -Headers (with an 's').  Maybe that's the issue. 🤔  

 

tyrone_owen_1
15,401 Views

Regarding the 's', good spot - though it was the v5 solution that worked - thank you

Public