< Summary - Kestrun — Combined Coverage

Information
Class: Public.Authentication.Add-KrApiKeyAuthentication
Assembly: Kestrun.PowerShell.Public
File(s): /home/runner/work/Kestrun/Kestrun/src/PowerShell/Kestrun/Public/Authentication/Add-KrApiKeyAuthentication.ps1
Tag: Kestrun/Kestrun@ca54e35c77799b76774b3805b6f075cdbc0c5fbe
Line coverage
0%
Covered lines: 0
Uncovered lines: 58
Coverable lines: 58
Total lines: 288
Line coverage: 0%
Branch coverage
N/A
Covered branches: 0
Total branches: 0
Branch coverage: N/A
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 09/08/2025 - 20:34:03 Line coverage: 54% (33/61) Total lines: 390 Tag: Kestrun/Kestrun@3790ee5884494a7a2a829344a47743e0bf492e7209/12/2025 - 16:20:13 Line coverage: 54% (33/61) Total lines: 391 Tag: Kestrun/Kestrun@bd014be0a15f3c9298922d2ff67068869adda2a010/13/2025 - 16:52:37 Line coverage: 0% (0/61) Total lines: 390 Tag: Kestrun/Kestrun@10d476bee71c71ad215bb8ab59f219887b5b4a5e12/12/2025 - 17:27:19 Line coverage: 0% (0/62) Total lines: 294 Tag: Kestrun/Kestrun@826bf9dcf9db118c5de4c78a3259bce9549f0dcd12/21/2025 - 06:07:10 Line coverage: 0% (0/63) Total lines: 303 Tag: Kestrun/Kestrun@8cf7f77e55fd1fd046ea4e5413eb9ef96e49fe6a01/21/2026 - 17:07:46 Line coverage: 0% (0/58) Total lines: 288 Tag: Kestrun/Kestrun@3f6f61710c7ef7d5953cab578fe699c1e5e01a36

Metrics

File(s)

/home/runner/work/Kestrun/Kestrun/src/PowerShell/Kestrun/Public/Authentication/Add-KrApiKeyAuthentication.ps1

#LineLine coverage
 1<#
 2    .SYNOPSIS
 3        Adds API key authentication to the Kestrun server.
 4    .DESCRIPTION
 5        Configures the Kestrun server to use API key authentication for incoming requests.
 6    .PARAMETER Server
 7        The Kestrun server instance to configure.
 8    .PARAMETER AuthenticationScheme
 9        The name of the API key authentication scheme.
 10    .PARAMETER DisplayName
 11        The display name of the API key authentication scheme.
 12    .PARAMETER Description
 13        A description of the API key authentication scheme.
 14    .PARAMETER Deprecated
 15        If specified, marks the authentication scheme as deprecated in OpenAPI documentation.
 16    .PARAMETER DocId
 17        The documentation IDs to associate with this authentication scheme in OpenAPI documentation.
 18    .PARAMETER Options
 19        The options to configure the API key authentication.
 20    .PARAMETER ScriptBlock
 21        A script block that contains the logic for validating the API key.
 22    .PARAMETER Code
 23        C# or VBNet code that contains the logic for validating the API key.
 24    .PARAMETER CodeLanguage
 25        The scripting language of the code used for validating the API key.
 26    .PARAMETER CodeFilePath
 27        Path to a file containing C# code that contains the logic for validating the API key.
 28    .PARAMETER StaticApiKey
 29        The expected API key to validate against.
 30    .PARAMETER ApiKeyName
 31        The name of the header to look for the API key.
 32    .PARAMETER AdditionalHeaderNames
 33        Additional headers to check for the API key.
 34    .PARAMETER AllowQueryStringFallback
 35        If specified, allows the API key to be provided in the query string.
 36    .PARAMETER AllowInsecureHttp
 37        If specified, allows the API key to be provided over HTTP instead of HTTPS.
 38    .PARAMETER EmitChallengeHeader
 39        If specified, emits a challenge header when the API key is missing or invalid.
 40    .PARAMETER ChallengeHeaderFormat
 41        The format of the challenge header to emit.
 42    .PARAMETER Logger
 43        A logger to use for logging authentication events.
 44    .PARAMETER ClaimPolicyConfig
 45        Configuration for claim policies to apply during authentication.
 46    .PARAMETER IssueClaimsScriptBlock
 47        A script block that contains the logic for issuing claims after successful authentication.
 48    .PARAMETER IssueClaimsCode
 49        C# or VBNet code that contains the logic for issuing claims after successful authentication.
 50    .PARAMETER IssueClaimsCodeLanguage
 51        The scripting language of the code used for issuing claims.
 52    .PARAMETER IssueClaimsCodeFilePath
 53        Path to a file containing the code that contains the logic for issuing claims after successful authentication
 54    .PARAMETER PassThru
 55        If specified, returns the modified server instance after adding the authentication.
 56    .EXAMPLE
 57        Add-KrApiKeyAuthentication -AuthenticationScheme 'MyApiKey' -StaticApiKey '12345' -ApiKeyName 'X-Api-Key'
 58        This example adds API key authentication to the server with the specified expected key and header name.
 59    .EXAMPLE
 60        Add-KrApiKeyAuthentication -AuthenticationScheme 'MyApiKey' -ScriptBlock {
 61            param($username, $password)
 62            return $username -eq 'admin' -and $password -eq 'password'
 63        }
 64        This example adds API key authentication using a script block to validate the API key.
 65    .EXAMPLE
 66        Add-KrApiKeyAuthentication -AuthenticationScheme 'MyApiKey' -Code @"
 67            return username == "admin" && password == "password";
 68        "@
 69        This example adds API key authentication using C# code to validate the API key.
 70    .EXAMPLE
 71        Add-KrApiKeyAuthentication -AuthenticationScheme 'MyApiKey' -CodeFilePath 'C:\path\to\code.cs'
 72        This example adds API key authentication using a C# code file to validate the API key.
 73    .LINK
 74        https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authentication.apikey.apikeyauthenticationopti
 75    .NOTES
 76        This cmdlet is used to configure API key authentication for the Kestrun server, allowing you to secure your APIs
 77#>
 78function Add-KrApiKeyAuthentication {
 79    [KestrunRuntimeApi('Definition')]
 80    [CmdletBinding(DefaultParameterSetName = 'ScriptBlock')]
 81    [OutputType([Kestrun.Hosting.KestrunHost])]
 82    param(
 83        [Parameter(ValueFromPipeline = $true)]
 84        [Kestrun.Hosting.KestrunHost]$Server,
 85
 86        [Parameter()]
 87        [string]$AuthenticationScheme = [Kestrun.Authentication.AuthenticationDefaults]::ApiKeySchemeName,
 88
 89        [Parameter()]
 90        [string]$DisplayName = [Kestrun.Authentication.AuthenticationDefaults]::ApiKeyDisplayName,
 91
 92        [Parameter(Mandatory = $false, ParameterSetName = 'ScriptBlock')]
 93        [Parameter(Mandatory = $false, ParameterSetName = 'CodeInline')]
 94        [Parameter(Mandatory = $false, ParameterSetName = 'StaticKey')]
 95        [Parameter(Mandatory = $false, ParameterSetName = 'CodeFile')]
 96        [string]$Description,
 97
 98        [Parameter(Mandatory = $false, ParameterSetName = 'ScriptBlock')]
 99        [Parameter(Mandatory = $false, ParameterSetName = 'CodeInline')]
 100        [Parameter(Mandatory = $false, ParameterSetName = 'StaticKey')]
 101        [Parameter(Mandatory = $false, ParameterSetName = 'CodeFile')]
 102        [switch]$Deprecated,
 103
 104        [Parameter()]
 105        [string[]]$DocId = [Kestrun.OpenApi.OpenApiDocDescriptor]::DefaultDocumentationIds,
 106
 107        # 1. Direct options
 108        [Parameter(Mandatory = $true, ParameterSetName = 'Options')]
 109        [Kestrun.Authentication.ApiKeyAuthenticationOptions]$Options,
 110
 111        # 2. Validation via ScriptBlock
 112        [Parameter(Mandatory = $true, ParameterSetName = 'ScriptBlock')]
 113        [scriptblock]$ScriptBlock,
 114
 115        # 3. Validation via inline code (C#/VB)
 116        [Parameter(Mandatory = $true, ParameterSetName = 'CodeInline')]
 117        [string]$Code,
 118
 119        [Parameter(ParameterSetName = 'CodeInline')]
 120        [Kestrun.Scripting.ScriptLanguage]$CodeLanguage = [Kestrun.Scripting.ScriptLanguage]::CSharp,
 121
 122        # 4. Validation via code file
 123        [Parameter(Mandatory = $true, ParameterSetName = 'CodeFile')]
 124        [string]$CodeFilePath,
 125
 126        # 5. Validation via static API key
 127        [Parameter(Mandatory = $true, ParameterSetName = 'StaticKey')]
 128        [string]$StaticApiKey,
 129
 130        [Parameter()]
 131        # Common API key config (all parameter sets)
 132        [Microsoft.OpenApi.ParameterLocation]$In = [Microsoft.OpenApi.ParameterLocation]::Header,
 133        [Parameter()]
 134        [string]$ApiKeyName,
 135        [Parameter()]
 136        [string[]]$AdditionalHeaderNames,
 137        [Parameter()]
 138        [switch]$AllowQueryStringFallback,
 139        [Parameter()]
 140        [switch]$AllowInsecureHttp,
 141        [Parameter()]
 142        [switch]$EmitChallengeHeader,
 143        [Parameter()]
 144        [Kestrun.Authentication.ApiKeyChallengeFormat]$ChallengeHeaderFormat,
 145
 146        [Parameter()]
 147        [Kestrun.Claims.ClaimPolicyConfig]$ClaimPolicyConfig,
 148
 149        # Optional "issue claims" configuration (independent from validation mode)
 150        [scriptblock]$IssueClaimsScriptBlock,
 151        [string]$IssueClaimsCode,
 152        [Kestrun.Scripting.ScriptLanguage]$IssueClaimsCodeLanguage = [Kestrun.Scripting.ScriptLanguage]::CSharp,
 153        [string]$IssueClaimsCodeFilePath,
 154
 155        [switch]$PassThru
 156    )
 157    begin {
 158        # Ensure the server instance is resolved
 0159        $Server = Resolve-KestrunServer -Server $Server
 160    }
 161    process {
 162        # Build Options only when not provided directly
 0163        if ($PSCmdlet.ParameterSetName -ne 'Options') {
 0164            $Options = [Kestrun.Authentication.ApiKeyAuthenticationOptions]::new()
 165            # Set host reference
 0166            $Options.Host = $Server
 0167            $Options.ValidateCodeSettings = [Kestrun.Authentication.AuthenticationCodeSettings]::new()
 168
 0169            switch ($PSCmdlet.ParameterSetName) {
 170                'ScriptBlock' {
 0171                    $Options.ValidateCodeSettings.Code = $ScriptBlock.ToString()
 0172                    $Options.ValidateCodeSettings.Language = [Kestrun.Scripting.ScriptLanguage]::PowerShell
 173                }
 174                'CodeInline' {
 0175                    $Options.ValidateCodeSettings.Code = $Code
 0176                    $Options.ValidateCodeSettings.Language = $CodeLanguage
 177                }
 178                'CodeFile' {
 0179                    if (-not (Test-Path -Path $CodeFilePath)) {
 0180                        throw "The specified code file path does not exist: $CodeFilePath"
 181                    }
 182                    # Infer language from file extension
 0183                    $Options.ValidateCodeSettings.Language = Resolve-KrCodeLanguageFromPath -Path $CodeFilePath
 184
 0185                    $Options.ValidateCodeSettings.Code = Get-Content -Path $CodeFilePath -Raw
 186                }
 187                'StaticKey' {
 0188                    $Options.StaticApiKey = $StaticApiKey
 189                }
 190            }
 191
 192            # Common API key options
 0193            if ($PSBoundParameters.ContainsKey('ApiKeyName')) {
 0194                $Options.ApiKeyName = $ApiKeyName
 195            }
 196
 197            # Set location of API key
 0198            $Options.In = $In
 199
 0200            if ($PSBoundParameters.ContainsKey('AdditionalHeaderNames') -and $AdditionalHeaderNames.Count -gt 0) {
 0201                $Options.AdditionalHeaderNames = $AdditionalHeaderNames
 202            }
 203
 0204            if ($AllowQueryStringFallback.IsPresent) {
 0205                $Options.AllowQueryStringFallback = $true
 206            }
 207
 0208            $Options.AllowInsecureHttp = $AllowInsecureHttp.IsPresent
 209
 0210            $Options.EmitChallengeHeader = $EmitChallengeHeader.IsPresent
 211
 0212            $Options.Deprecated = $Deprecated.IsPresent
 213
 0214            if ($PSBoundParameters.ContainsKey('ChallengeHeaderFormat')) {
 0215                $Options.ChallengeHeaderFormat = $ChallengeHeaderFormat
 216            }
 217
 0218            if ($PSBoundParameters.ContainsKey('ClaimPolicyConfig')) {
 0219                $Options.ClaimPolicyConfig = $ClaimPolicyConfig
 220            }
 221
 0222            if (-not ([string]::IsNullOrWhiteSpace($Description))) {
 0223                $Options.Description = $Description
 224            }
 225
 226            # Optional issue-claims settings (single-choice)
 0227            $issueModes = @()
 0228            if ($PSBoundParameters.ContainsKey('IssueClaimsScriptBlock')) { $issueModes += 'ScriptBlock' }
 0229            if ($PSBoundParameters.ContainsKey('IssueClaimsCode')) { $issueModes += 'Code' }
 0230            if ($PSBoundParameters.ContainsKey('IssueClaimsCodeFilePath')) { $issueModes += 'File' }
 231
 0232            if ($issueModes.Count -gt 1) {
 0233                throw 'Specify only one of -IssueClaimsScriptBlock, -IssueClaimsCode, or -IssueClaimsCodeFilePath.'
 234            }
 235
 0236            if ($issueModes.Count -eq 1) {
 0237                $Options.IssueClaimsCodeSettings = [Kestrun.Authentication.AuthenticationCodeSettings]::new()
 238
 0239                switch ($issueModes[0]) {
 240                    'ScriptBlock' {
 0241                        $Options.IssueClaimsCodeSettings.Code = $IssueClaimsScriptBlock.ToString()
 0242                        $Options.IssueClaimsCodeSettings.Language = [Kestrun.Scripting.ScriptLanguage]::PowerShell
 243                    }
 244                    'Code' {
 0245                        $Options.IssueClaimsCodeSettings.Code = $IssueClaimsCode
 0246                        $Options.IssueClaimsCodeSettings.Language = $IssueClaimsCodeLanguage
 247                    }
 248                    'File' {
 0249                        if (-not (Test-Path -Path $IssueClaimsCodeFilePath)) {
 0250                            throw "The specified issue-claims code file path does not exist: $IssueClaimsCodeFilePath"
 251                        }
 252
 0253                        $issueExt = [System.IO.Path]::GetExtension($IssueClaimsCodeFilePath)
 254
 0255                        switch ($issueExt.ToLowerInvariant()) {
 256                            '.ps1' {
 0257                                $Options.IssueClaimsCodeSettings.Language = [Kestrun.Scripting.ScriptLanguage]::PowerShe
 258                            }
 259                            '.cs' {
 0260                                $Options.IssueClaimsCodeSettings.Language = [Kestrun.Scripting.ScriptLanguage]::CSharp
 261                            }
 262                            '.vb' {
 0263                                $Options.IssueClaimsCodeSettings.Language = [Kestrun.Scripting.ScriptLanguage]::VisualBa
 264                            }
 265                            default {
 0266                                throw "Unsupported '$issueExt' code file extension for issue-claims."
 267                            }
 268                        }
 269
 0270                        $Options.IssueClaimsCodeSettings.Code = Get-Content -Path $IssueClaimsCodeFilePath -Raw
 271                    }
 272                }
 273            }
 274
 275            # OpenAPI documentation IDs
 0276            $Options.DocumentationId = $DocId
 277        }
 278
 279        # Add API key authentication to the server
 0280        [Kestrun.Hosting.KestrunHostAuthnExtensions]::AddApiKeyAuthentication(
 0281            $Server, $AuthenticationScheme, $DisplayName, $Options ) | Out-Null
 282
 283        # Return the modified server instance if PassThru is specified
 0284        if ($PassThru.IsPresent) {
 0285            return $Server
 286        }
 287    }
 288}

Methods/Properties

Add-KrApiKeyAuthentication()