PolarisPowerShell

Add basic authentication for the REST API built using PowerShell Polaris module.

Off late, I am busy in Azure Infrastructure Projects and in parallel I spend my free hours with PowerShell Polaris and PSHTML modules. All my learning is to help Ops guys to assist business people to work on Azure or Office365 products at ease. If you are new to Polaris and PSHTML make use of below links.

Get Started Polaris

Get Started PSHTML

No PSHTML contents are added in this blog article. However, you can refer here to add login page for your application using PSHTML.

I thank  @bgelens and @tiberriver256 and for sharing their code and ideas. Through that I picked few lines for my project.

Requirement

Share user id and password with developers or IT Pro (consumers of REST API) as clear text. So, they can use in their code get authenticated to REST end point.  This is how I hook up with REST endpoint as a consumer using encoded basic authentication!

It’s simple code in PowerShell – And, we all know it!

Client Side Code

$Encoded = [Convert]::ToBase64String(
    [System.Text.ASCIIEncoding]::ASCII.GetBytes(
        [string]::Format("{0}:{1}", 'Admin', 'Password'
        )
    )
)
$Req = Invoke-RestMethod -Uri "http://localhost:8080/" -Method Get -Headers @{"Authorization" = "Basic $Encoded"}
$Req

Server Set Up for Basic Authentication

Import-Module Polaris -Verbose
New-PolarisGetRoute -Path "/" -Scriptblock {
    if ($Request.Headers['Authorization'] -ne 'Basic QWRtaW46UGFzc3dvcmQ=') {
        $Result = [pscustomobject]@{
            Message = "Failed - Invalid Auth 401 Found!"
            Help    = "Contact System."
            Email   = "chendrayan.exchange@hotmail.com"
        }
        $Response.Send(($Result | ConvertTo-Json))
    }
    else {
        $Result = [pscustomobject]@{
            Message = "Success - Valid Auth 200 Found!"
        }
        $Response.Send(($Result | ConvertTo-Json))
    }
}

Start-Polaris -Port 8080

Enjoy PowerShell!

Leave a Reply

Your email address will not be published. Required fields are marked *