< 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@0d738bf294e6281b936d031e1979d928007495ff
Line coverage
0%
Covered lines: 0
Uncovered lines: 62
Coverable lines: 62
Total lines: 294
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 08/26/2025 - 14:53:17 Line coverage: 54% (33/61) Total lines: 389 Tag: Kestrun/Kestrun@78d1e497d8ba989d121b57aa39aa3c6b22de743109/04/2025 - 22:37:32 Line coverage: 54% (33/61) Total lines: 390 Tag: Kestrun/Kestrun@afb7aadc0a8a42bfa2b51ea62c8a6e2cf63faec609/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@826bf9dcf9db118c5de4c78a3259bce9549f0dcd

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 DocId
 15        The documentation IDs to associate with this authentication scheme in OpenAPI documentation.
 16    .PARAMETER Options
 17        The options to configure the API key authentication.
 18    .PARAMETER ScriptBlock
 19        A script block that contains the logic for validating the API key.
 20    .PARAMETER Code
 21        C# or VBNet code that contains the logic for validating the API key.
 22    .PARAMETER CodeLanguage
 23        The scripting language of the code used for validating the API key.
 24    .PARAMETER CodeFilePath
 25        Path to a file containing C# code that contains the logic for validating the API key.
 26    .PARAMETER StaticApiKey
 27        The expected API key to validate against.
 28    .PARAMETER ApiKeyName
 29        The name of the header to look for the API key.
 30    .PARAMETER AdditionalHeaderNames
 31        Additional headers to check for the API key.
 32    .PARAMETER AllowQueryStringFallback
 33        If specified, allows the API key to be provided in the query string.
 34    .PARAMETER AllowInsecureHttp
 35        If specified, allows the API key to be provided over HTTP instead of HTTPS.
 36    .PARAMETER EmitChallengeHeader
 37        If specified, emits a challenge header when the API key is missing or invalid.
 38    .PARAMETER ChallengeHeaderFormat
 39        The format of the challenge header to emit.
 40    .PARAMETER Logger
 41        A logger to use for logging authentication events.
 42    .PARAMETER ClaimPolicyConfig
 43        Configuration for claim policies to apply during authentication.
 44    .PARAMETER IssueClaimsScriptBlock
 45        A script block that contains the logic for issuing claims after successful authentication.
 46    .PARAMETER IssueClaimsCode
 47        C# or VBNet code that contains the logic for issuing claims after successful authentication.
 48    .PARAMETER IssueClaimsCodeLanguage
 49        The scripting language of the code used for issuing claims.
 50    .PARAMETER IssueClaimsCodeFilePath
 51        Path to a file containing the code that contains the logic for issuing claims after successful authentication
 52    .PARAMETER PassThru
 53        If specified, returns the modified server instance after adding the authentication.
 54    .EXAMPLE
 55        Add-KrApiKeyAuthentication -AuthenticationScheme 'MyApiKey' -StaticApiKey '12345' -ApiKeyName 'X-Api-Key'
 56        This example adds API key authentication to the server with the specified expected key and header name.
 57    .EXAMPLE
 58        Add-KrApiKeyAuthentication -AuthenticationScheme 'MyApiKey' -ScriptBlock {
 59            param($username, $password)
 60            return $username -eq 'admin' -and $password -eq 'password'
 61        }
 62        This example adds API key authentication using a script block to validate the API key.
 63    .EXAMPLE
 64        Add-KrApiKeyAuthentication -AuthenticationScheme 'MyApiKey' -Code @"
 65            return username == "admin" && password == "password";
 66        "@
 67        This example adds API key authentication using C# code to validate the API key.
 68    .EXAMPLE
 69        Add-KrApiKeyAuthentication -AuthenticationScheme 'MyApiKey' -CodeFilePath 'C:\path\to\code.cs'
 70        This example adds API key authentication using a C# code file to validate the API key.
 71    .LINK
 72        https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authentication.apikey.apikeyauthenticationopti
 73    .NOTES
 74        This cmdlet is used to configure API key authentication for the Kestrun server, allowing you to secure your APIs
 75#>
 76function Add-KrApiKeyAuthentication {
 77    [KestrunRuntimeApi('Definition')]
 78    [CmdletBinding(DefaultParameterSetName = 'ScriptBlock')]
 79    [OutputType([Kestrun.Hosting.KestrunHost])]
 80    param(
 81        [Parameter(ValueFromPipeline = $true)]
 82        [Kestrun.Hosting.KestrunHost]$Server,
 83
 84        [Parameter()]
 85        [string]$AuthenticationScheme = [Kestrun.Authentication.AuthenticationDefaults]::ApiKeySchemeName,
 86
 87        [Parameter()]
 88        [string]$DisplayName = [Kestrun.Authentication.AuthenticationDefaults]::ApiKeyDisplayName,
 89
 90        [Parameter(Mandatory = $false, ParameterSetName = 'ScriptBlock')]
 91        [Parameter(Mandatory = $false, ParameterSetName = 'CodeInline')]
 92        [Parameter(Mandatory = $false, ParameterSetName = 'StaticKey')]
 93        [Parameter(Mandatory = $false, ParameterSetName = 'CodeFile')]
 94        [string]$Description,
 95
 96        [Parameter()]
 97        [string[]]$DocId = [Kestrun.Authentication.IOpenApiAuthenticationOptions]::DefaultDocumentationIds,
 98
 99        # 1. Direct options
 100        [Parameter(Mandatory = $true, ParameterSetName = 'Options')]
 101        [Kestrun.Authentication.ApiKeyAuthenticationOptions]$Options,
 102
 103        # 2. Validation via ScriptBlock
 104        [Parameter(Mandatory = $true, ParameterSetName = 'ScriptBlock')]
 105        [scriptblock]$ScriptBlock,
 106
 107        # 3. Validation via inline code (C#/VB)
 108        [Parameter(Mandatory = $true, ParameterSetName = 'CodeInline')]
 109        [string]$Code,
 110
 111        [Parameter(ParameterSetName = 'CodeInline')]
 112        [Kestrun.Scripting.ScriptLanguage]$CodeLanguage = [Kestrun.Scripting.ScriptLanguage]::CSharp,
 113
 114        # 4. Validation via code file
 115        [Parameter(Mandatory = $true, ParameterSetName = 'CodeFile')]
 116        [string]$CodeFilePath,
 117
 118        # 5. Validation via static API key
 119        [Parameter(Mandatory = $true, ParameterSetName = 'StaticKey')]
 120        [string]$StaticApiKey,
 121
 122        [Parameter()]
 123        # Common API key config (all parameter sets)
 124        [Microsoft.OpenApi.ParameterLocation]$In = [Microsoft.OpenApi.ParameterLocation]::Header,
 125        [Parameter()]
 126        [string]$ApiKeyName,
 127        [Parameter()]
 128        [string[]]$AdditionalHeaderNames,
 129        [Parameter()]
 130        [switch]$AllowQueryStringFallback,
 131        [Parameter()]
 132        [switch]$AllowInsecureHttp,
 133        [Parameter()]
 134        [switch]$EmitChallengeHeader,
 135        [Parameter()]
 136        [Kestrun.Authentication.ApiKeyChallengeFormat]$ChallengeHeaderFormat,
 137
 138        [Parameter()]
 139        [Kestrun.Claims.ClaimPolicyConfig]$ClaimPolicyConfig,
 140
 141        # Optional "issue claims" configuration (independent from validation mode)
 142        [scriptblock]$IssueClaimsScriptBlock,
 143        [string]$IssueClaimsCode,
 144        [Kestrun.Scripting.ScriptLanguage]$IssueClaimsCodeLanguage = [Kestrun.Scripting.ScriptLanguage]::CSharp,
 145        [string]$IssueClaimsCodeFilePath,
 146
 147        [switch]$PassThru
 148    )
 149    begin {
 150        # Ensure the server instance is resolved
 0151        $Server = Resolve-KestrunServer -Server $Server
 152    }
 153    process {
 154        # Build Options only when not provided directly
 0155        if ($PSCmdlet.ParameterSetName -ne 'Options') {
 0156            $Options = [Kestrun.Authentication.ApiKeyAuthenticationOptions]::new()
 157            # Set host reference
 0158            $Options.Host = $Server
 0159            $Options.ValidateCodeSettings = [Kestrun.Authentication.AuthenticationCodeSettings]::new()
 160
 0161            switch ($PSCmdlet.ParameterSetName) {
 162                'ScriptBlock' {
 0163                    $Options.ValidateCodeSettings.Code = $ScriptBlock.ToString()
 0164                    $Options.ValidateCodeSettings.Language = [Kestrun.Scripting.ScriptLanguage]::PowerShell
 165                }
 166                'CodeInline' {
 0167                    $Options.ValidateCodeSettings.Code = $Code
 0168                    $Options.ValidateCodeSettings.Language = $CodeLanguage
 169                }
 170                'CodeFile' {
 0171                    if (-not (Test-Path -Path $CodeFilePath)) {
 0172                        throw "The specified code file path does not exist: $CodeFilePath"
 173                    }
 174
 0175                    $extension = [System.IO.Path]::GetExtension($CodeFilePath)
 176
 0177                    switch ($extension.ToLowerInvariant()) {
 178                        '.ps1' {
 0179                            $Options.ValidateCodeSettings.Language = [Kestrun.Scripting.ScriptLanguage]::PowerShell
 180                        }
 181                        '.cs' {
 0182                            $Options.ValidateCodeSettings.Language = [Kestrun.Scripting.ScriptLanguage]::CSharp
 183                        }
 184                        '.vb' {
 0185                            $Options.ValidateCodeSettings.Language = [Kestrun.Scripting.ScriptLanguage]::VisualBasic
 186                        }
 187                        default {
 0188                            throw "Unsupported '$extension' code file extension for validation."
 189                        }
 190                    }
 191
 0192                    $Options.ValidateCodeSettings.Code = Get-Content -Path $CodeFilePath -Raw
 193                }
 194                'StaticKey' {
 0195                    $Options.StaticApiKey = $StaticApiKey
 196                }
 197            }
 198
 199            # Common API key options
 0200            if ($PSBoundParameters.ContainsKey('ApiKeyName')) {
 0201                $Options.ApiKeyName = $ApiKeyName
 202            }
 203
 204            # Set location of API key
 0205            $Options.In = $In
 206
 0207            if ($PSBoundParameters.ContainsKey('AdditionalHeaderNames') -and $AdditionalHeaderNames.Count -gt 0) {
 0208                $Options.AdditionalHeaderNames = $AdditionalHeaderNames
 209            }
 210
 0211            if ($AllowQueryStringFallback.IsPresent) {
 0212                $Options.AllowQueryStringFallback = $true
 213            }
 214
 0215            $Options.AllowInsecureHttp = $AllowInsecureHttp.IsPresent
 216
 0217            $Options.EmitChallengeHeader = $EmitChallengeHeader.IsPresent
 218
 219
 0220            if ($PSBoundParameters.ContainsKey('ChallengeHeaderFormat')) {
 0221                $Options.ChallengeHeaderFormat = $ChallengeHeaderFormat
 222            }
 223
 0224            if ($PSBoundParameters.ContainsKey('ClaimPolicyConfig')) {
 0225                $Options.ClaimPolicyConfig = $ClaimPolicyConfig
 226            }
 227
 0228            if (-not ([string]::IsNullOrWhiteSpace($Description))) {
 0229                $Options.Description = $Description
 230            }
 231
 232            # Optional issue-claims settings (single-choice)
 0233            $issueModes = @()
 0234            if ($PSBoundParameters.ContainsKey('IssueClaimsScriptBlock')) { $issueModes += 'ScriptBlock' }
 0235            if ($PSBoundParameters.ContainsKey('IssueClaimsCode')) { $issueModes += 'Code' }
 0236            if ($PSBoundParameters.ContainsKey('IssueClaimsCodeFilePath')) { $issueModes += 'File' }
 237
 0238            if ($issueModes.Count -gt 1) {
 0239                throw 'Specify only one of -IssueClaimsScriptBlock, -IssueClaimsCode, or -IssueClaimsCodeFilePath.'
 240            }
 241
 0242            if ($issueModes.Count -eq 1) {
 0243                $Options.IssueClaimsCodeSettings = [Kestrun.Authentication.AuthenticationCodeSettings]::new()
 244
 0245                switch ($issueModes[0]) {
 246                    'ScriptBlock' {
 0247                        $Options.IssueClaimsCodeSettings.Code = $IssueClaimsScriptBlock.ToString()
 0248                        $Options.IssueClaimsCodeSettings.Language = [Kestrun.Scripting.ScriptLanguage]::PowerShell
 249                    }
 250                    'Code' {
 0251                        $Options.IssueClaimsCodeSettings.Code = $IssueClaimsCode
 0252                        $Options.IssueClaimsCodeSettings.Language = $IssueClaimsCodeLanguage
 253                    }
 254                    'File' {
 0255                        if (-not (Test-Path -Path $IssueClaimsCodeFilePath)) {
 0256                            throw "The specified issue-claims code file path does not exist: $IssueClaimsCodeFilePath"
 257                        }
 258
 0259                        $issueExt = [System.IO.Path]::GetExtension($IssueClaimsCodeFilePath)
 260
 0261                        switch ($issueExt.ToLowerInvariant()) {
 262                            '.ps1' {
 0263                                $Options.IssueClaimsCodeSettings.Language = [Kestrun.Scripting.ScriptLanguage]::PowerShe
 264                            }
 265                            '.cs' {
 0266                                $Options.IssueClaimsCodeSettings.Language = [Kestrun.Scripting.ScriptLanguage]::CSharp
 267                            }
 268                            '.vb' {
 0269                                $Options.IssueClaimsCodeSettings.Language = [Kestrun.Scripting.ScriptLanguage]::VisualBa
 270                            }
 271                            default {
 0272                                throw "Unsupported '$issueExt' code file extension for issue-claims."
 273                            }
 274                        }
 275
 0276                        $Options.IssueClaimsCodeSettings.Code = Get-Content -Path $IssueClaimsCodeFilePath -Raw
 277                    }
 278                }
 279            }
 280
 281            # OpenAPI documentation IDs
 0282            $Options.DocumentationId = $DocId
 283        }
 284
 285        # Add API key authentication to the server
 0286        [Kestrun.Hosting.KestrunHostAuthnExtensions]::AddApiKeyAuthentication(
 0287            $Server, $AuthenticationScheme, $DisplayName, $Options ) | Out-Null
 288
 289        # Return the modified server instance if PassThru is specified
 0290        if ($PassThru.IsPresent) {
 0291            return $Server
 292        }
 293    }
 294}

Methods/Properties

Add-KrApiKeyAuthentication()