Basic (PowerShell)
Define a Basic auth scheme with a PowerShell script block validating username/password.
Prerequisites: see Introduction.
Full source
File: pwsh/tutorial/examples/8.1-Basic-PS.ps1
<#
Sample: Basic Authentication (PowerShell)
Purpose: Demonstrates creating a Basic authentication scheme using a PowerShell script block for credential validation.
File: 8.1-Basic-PS.ps1
Notes: Plain-text password comparison for tutorial purposes only. Use secure storage in production.
#>
param(
[int]$Port = 5000,
[IPAddress]$IPAddress = [IPAddress]::Loopback
)
# 1. (Optional) Logging pipeline
New-KrLogger |
Add-KrSinkConsole |
Register-KrLogger -Name 'console' -SetAsDefault | Out-Null
# 2. Create server host
New-KrServer -Name 'Auth Basic PS'
# 3. Add HTTP listener on specified port and IP address
Add-KrEndpoint -Port $Port -IPAddress $IPAddress
# 4. Define Basic auth scheme with inline validation script
Add-KrBasicAuthentication -Name 'PowershellBasic' -Realm 'Demo' -AllowInsecureHttp -ScriptBlock {
param($Username, $Password)
$Username -eq 'admin' -and $Password -eq 'password'
}
# 5. Finalize configuration (build internal pipeline)
Enable-KrConfiguration
# 6. Map secured route group using the scheme
Add-KrRouteGroup -Prefix '/secure/ps' -AuthorizationSchema 'PowershellBasic' {
Add-KrMapRoute -Verbs Get -Pattern '/hello' -ScriptBlock {
Write-KrTextResponse -InputObject "Hello, $( $Context.User.Identity.Name )!" -ContentType 'text/plain'
}
}
# 7. Start server (Ctrl+C to stop)
Start-KrServer -CloseLogsOnExit
Step-by-step
- Create server & listener (HTTP 5000).
- Define a Basic scheme with
Add-KrBasicAuthentication -ScriptBlock. - Enable configuration.
- Protect route group prefix
/secure/pswith the scheme. - Map
/helloroute returning user identity. - Start server.
Try it
$creds = 'admin:password'
$basic = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes($creds))
Invoke-WebRequest -Uri http://127.0.0.1:5000/secure/ps/hello -Headers @{ Authorization = $basic } |
Select-Object -ExpandProperty Content
Expected: greeting containing username.
References
- Add-KrBasicAuthentication
- Add-KrRouteGroup
- Add-KrMapRoute
- New-KrServer
- Add-KrEndpoint
- Enable-KrConfiguration
- Start-KrServer
Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
| 401 Unauthorized | Missing/invalid header | Supply Authorization: Basic <base64> |
| Always 401 | Script block logic wrong | Validate credential comparison |
| Empty identity | No authenticated user | Ensure scheme name matches route group |
Previous / Next
- Previous: Endpoints
- Next: Basic (C# / VB.NET)