Before we start looking at the code, let’s understand what Basic Authentication is all about.

Basic Authentication, in simple words, is a way of providing credentials (i.e. username and password) while making a request. See how it works in the diagram below:

Basic Authentication Process Flowchart

 

Now, let’s see how we can implement Basic Authentication using Powershell.

function Get-Data([string]$username, [string]$password, [string]$url) {

  # Step 1. Create a username:password pair
  $credPair = "$($username):$($password)"

  # Step 2. Encode the pair to Base64 string
  $encodedCredentials = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($credPair))

  # Step 3. Form the header and add the Authorization attribute to it
  $headers = @{ Authorization = "Basic $encodedCredentials" }

  # Step 4. Make the GET request
  $responseData = Invoke-WebRequest -Uri $url -Method Get -Headers $headers -UseBasicParsing

  return $responseData
}

You can use the above function in the following way:

$data = Get-Data -username user -password pass -url https://somedomain.com/posts
$dataToDict = $data | ConvertFrom-Json

In case, you’re getting the following error while calling the Get-Data method:


Invoke-WebRequest : The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

Add the following line of code outside your function:

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

You can add additional attributes while forming the header like Content-Type, etc.

Advertisements